Benutzer:MovGP0/Logging

 MovGP0   Über mich   Hilfen   Artikel   Weblinks   Literatur   Zitate   Notizen   Programmierung   MSCert   Physik 


Logging

Log Levels

Log4J Log Levels
Level Description
OFF The highest possible rank and is intended to turn off logging.
FATAL Severe errors that cause premature termination. Expect these to be immediately visible on a status console.
ERROR Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
WARN Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
INFO Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
DEBUG Detailed information on the flow through the system. Expect these to be written to logs only.
TRACE Most detailed information. Expect these to be written to logs only.

NuGet-Pakete

NLog log4net
  • NLog
  • NLog.Config
  • NLog.Schema
  • log4net
  • log4net.Ext.Json

Konfiguration

NLog log4net
app.config / web.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>

  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <include file="NLog.config" />
  </nlog>

  <appSettings>
  </appSettings>
NLog.config
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <targets>
    <target xsi:type="EventLog" name="eventLog" layout="${message}${newline}${exception:format=ToString}" source="${appName}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Error" writeTo="eventLog" />
  </rules>
</nlog>
app.config / web.config
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4net>
    <!-- base config -->
  </log4net>

  <appSettings>
     <add key="log4net.Config" value="log4net.config" />
  </appSettings>
log4net.config
<log4net debug="true">
  <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="EventLogAppender" />
  </root>
</log4net>

Log4Net Debugging

  <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add name="textWriterTraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="%TEMP%\log.txt" />
      </listeners>
    </trace>
  </system.diagnostics>

  <appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
  </appSettings>


Common Logging

  <configSections>
    <sectionGroup name="common">
      <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
    </sectionGroup>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    <!-- ... -->
  </configSection>
  <!-- ... -->
  <common>
    <logging>
      <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net1211">
        choices are INLINE, FILE, FILE-WATCH, EXTERNAL
        otherwise BasicConfigurer.Configure is used
        log4net configuration file is specified with key configFile
        <arg key="configType" value="FILE-WATCH" />
        <arg key="configFile" value="~/Config/log4net.config"/>
        <arg key="level" value="INFO" />
      </factoryAdapter>
    </logging>
  </common>
  <!-- ... -->

Bootstrapping

Bootstrapping von log4net
log4net
in Global.asax
protected void Application_Start(Object sender, EventArgs e)
{
   log4net.Config.XmlConfigurator.Configure();
}
oder AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Manuelles Laden der Konfiguration
(falls kein Zugriff auf web.config)
NLog log4net
using(var config = Assembly.GetExecutingAssembly().GetManifestResourceStream("nlog.config"))
{
   var reader = XmlReader.Create(config);
   NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(reader, true));
}
using(var config = Assembly.GetExecutingAssembly().GetManifestResourceStream("log4net.config"))
{
   XmlConfigurator.Configure(config);
}

PostSharp-Aspekt

NLog Log4Net
using NLog;
using PostSharp.Aspects;
using System;

namespace .....
{
    [Serializable]
    public class LogAttribute : OnMethodBoundaryAspect
    {
        [NonSerialized]
        private Logger logger;

        public LogAttribute()
        {
            logger = LogManager.GetCurrentClassLogger();
        }

        public override void OnEntry(MethodExecutionArgs args)
        {
            logger.Trace(string.Format("Entering {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name));
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            logger.Trace(string.Format("Leaving {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name));
        }

        public override void OnException(MethodExecutionArgs args)
        {
            logger.Error(args.Exception.Message, args.Exception);
        }
    }
}
using NLog;
using PostSharp.Aspects;
using System;

namespace .....
{
    [Serializable]
    public class LogAttribute : OnMethodBoundaryAspect
    {
        [NonSerialized]
        private ILog logger;

        public LogAttribute()
        {
            logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        }

        public override void OnEntry(MethodExecutionArgs args)
        {
            logger.Trace(string.Format("Entering {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name));
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            logger.Trace(string.Format("Leaving {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name));
        }

        public override void OnException(MethodExecutionArgs args)
        {
            logger.Error(args.Exception.Message, args.Exception);
        }
    }
}

Global Exception Logging

Console Application
static void Main() {
    AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
    // ...
}
ASP.NET Application

Content Disclaimer

Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.

  1. The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
  2. There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
  3. It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
  4. Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
  5. Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.