[Asp.net 5] Logging-Implementation of other log systems, asp. netlogging-

Source: Internet
Author: User
Tags log4net

[Asp.net 5] Logging-Implementation of other log systems, asp. netlogging-

Microsoft. Framework. Logging. NLog

Using Nlog to expand the log system: As described in the previous section, two interfaces ILogger and ILoggerProvider must be implemented for the extended log system. Therefore, there are no exceptions in the current project. NLogLoggerProvider implements ILoggerProvider and internal Logger implements ILogger. The source code is as follows:

Public class NLogLoggerProvider: ILoggerProvider {private readonly LogFactory _ logFactory; public NLogLoggerProvider (LogFactory logFactory) {_ logFactory = logFactory;} public ILogger CreateLogger (string name) {return new Logger (_ logFactory. getLogger (name);} private class Logger: ILogger {private readonly global: NLog. logger _ logger; public Logger (global: NLog. logger logger) {_ logger = log Ger;} public void Log (LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter) {var nLogLogLevel = GetLogLevel (logLevel ); var message = string. empty; if (formatter! = Null) {message = formatter (state, exception);} else {message = LogFormatter. Formatter (state, exception);} if (! String. isNullOrEmpty (message) {var eventInfo = LogEventInfo. create (nLogLogLevel, _ logger. name, message, exception); eventInfo. properties ["EventId"] = eventId; _ logger. log (eventInfo) ;}} public bool IsEnabled (LogLevel logLevel) {return _ logger. isEnabled (GetLogLevel (logLevel);} private global: NLog. logLevel GetLogLevel (LogLevel logLevel) {switch (logLevel) {case LogLevel. verbose: return global: NLog. logLevel. debug; case LogLevel. information: return global: NLog. logLevel. info; case LogLevel. warning: return global: NLog. logLevel. warn; case LogLevel. error: return global: NLog. logLevel. error; case LogLevel. critical: return global: NLog. logLevel. fatal;} return global: NLog. logLevel. debug;} public IDisposable BeginScopeImpl ([NotNull] object state) {return NestedDiagnosticsContext. push (state. toString ());}}}NLog

This code is easy to understand and can be explained. Note that LogFactory is the NLog factory.
Below we will mainly compare NLog with the well-known Log4net. (There are many hearsay. please correct me)

  • It is not recommended to use it directly. Use the door class packaging (that is, the internal Logger class of Microsoft. Framework. Logging. NLog in this section is actually the front of the Nlog log)
  • If the current system uses a log system, we recommend that you use the original log system (more log4net applications). We recommend that you use Nlog for all new projects.
  • From the Initialization Configuration, Nlog is simpler than log4net.
  • In terms of function strength, it can be split into different colors.
  • From the open source code update degree perspective: Nlog and on github open source (https://github.com/nlog), log4net Open Source on Apache (Http://logging.apache.org/log4net/download_log4net.cgi). However, Nlog is updated and supported. there are also many versions of. net. log4net does not feel updated for a long time. The core version is still. net2.0 (this is not a hearsay, but the conclusion of Lou pig's own download of the source code)
  • It is said that log4net is faster than Nlog when using synchronous log recording, but Nlog can enable asynchronous log, and the speed will not exceed log4net.

The following are some blog posts for the author's reference.

  • Log4net vs. Nlog [closed] (proud leopard)
  • NLog 2.0.0.2000 instance used (the reply part is the main reference and the main body is about the use of Nlog)
  • NLog article series-series articles directory and brief introduction (Nlog learning reference)

Microsoft. Framework. Logging. Console

In fact, there are not many logs written directly on the console, so this log system may not be widely used. However, there are still a lot of code that can be circled: using the IConsole interface and the LogConsole class. Generally, we will only implement the ILogger and ILoggerProvider interfaces, that is, the write implementation classes ConsoleLogger and ConsoleLoggerProvider. However, ConsoleLogger is only responsible for recording logical operations. operations on the media belong to the IConsole. If ConsoleLogger and LogConsole are softened together, the problem is not serious; however, this clearly violates the single responsibility principle of object-oriented design. Therefore, although the sparrow is small and dirty, these small classes can also reflect the ability of object-oriented.

Microsoft. Framework. Logging. TraceSource

This is a strange thing for me, although it comes with. net, and it is available from 1.0. When it is initially used, Debug and Trace are used for tracking and recording. When it reaches. net2.0, TraceSource is used as the enhanced version of Debug and Trace.

TraceSource Configuration:

  • Listeners: controls the output direction of trace information (which can be: Listener, DefaultTraceListener, EventLogTraceListener, WebPageTraceListener, and so on). The subclass of listener includes leletracelistener, listener, listener, EventSchemaTraceListener)
  • Switch: Information Filtering Switch, including BooleanSwitch, TraceSwitch, and SourceSwitch

References:

  • Use of Trace, Debug, and TraceSource and log Design
  • TraceSource Records Program logs
  • TraceSource class

Let's look back at the Microsoft. Framework. Logging. TraceSource code.

Public class events: ILoggerProvider {private readonly SourceSwitch _ rootSourceSwitch; private readonly TraceListener _ rootTraceListener; private readonly ConcurrentDictionary <string, TraceSource> _ sources = new ConcurrentDictionary <string, TraceSource>. ordinalIgnoreCase); public TraceSourceLoggerProvider ([NotNull] SourceSwitch rootSourceSwitch, [NotNull] TraceList Ener rootTraceListener) {_ rootSourceSwitch = rootSourceSwitch; _ rootTraceListener = rootTraceListener;} public ILogger CreateLogger (string name) {return new TraceSourceLogger (GetOrAddTraceSource (name ));} private TraceSource GetOrAddTraceSource (string name) {return _ sources. getOrAdd (name, InitializeTraceSource);} private TraceSource InitializeTraceSource (string traceSourceName) {var traceSou Rce = new TraceSource (traceSourceName); string parentSourceName = ParentSourceName (traceSourceName); if (string. isNullOrEmpty (parentSourceName) {if (HasDefaultSwitch (traceSource) {traceSource. switch = _ rootSourceSwitch;} if (_ rootTraceListener! = Null) {traceSource. listeners. add (_ rootTraceListener) ;}} else {if (hasdefalistlisteners (traceSource) {TraceSource parentTraceSource = GetOrAddTraceSource (parentSourceName); traceSource. listeners. clear (); traceSource. listeners. addRange (parentTraceSource. listeners);} if (HasDefaultSwitch (traceSource) {TraceSource parentTraceSource = GetOrAddTraceSource (parentSourceName); traceSource. switch = ParentTraceSource. Switch;} return traceSource;} private static string ParentSourceName (string traceSourceName) {int indexOfLastDot = traceSourceName. LastIndexOf ('.'); return indexOfLastDot =-1? Null: traceSourceName. substring (0, indexOfLastDot);} private static bool hasdefalistlisteners (TraceSource traceSource) {return traceSource. listeners. count = 1 & amp; traceSource. listeners [0] is DefaultTraceListener;} private static bool HasDefaultSwitch (TraceSource traceSource) {return string. isNullOrEmpty (traceSource. switch. displayName) = string. isNullOrEmpty (traceSource. name) & traceSource. switch. level = SourceLevels. off ;}}Extends internal class TraceSourceLogger: ILogger {private readonly TraceSource _ traceSource; public TraceSourceLogger (TraceSource traceSource) {_ traceSource = traceSource;} public void Log (LogLevel logLevel, int eventId, object state, exception exception, Func <object, Exception, string> formatter) {if (! IsEnabled (logLevel) {return;} var message = string. Empty; if (formatter! = Null) {message = formatter (state, exception);} else {if (state! = Null) {message + = state;} if (exception! = Null) {message + = Environment. NewLine + exception;} if (! String. isNullOrEmpty (message) {_ traceSource. traceEvent (GetEventType (logLevel), eventId, message) ;}} public bool IsEnabled (LogLevel logLevel) {var traceEventType = GetEventType (logLevel); return _ traceSource. switch. shouldTrace (traceEventType);} private static TraceEventType GetEventType (LogLevel logLevel) {switch (logLevel) {case LogLevel. critical: return TraceEventType. critical; case LogLevel. error: return TraceEventType. error; case LogLevel. warning: return TraceEventType. warning; case LogLevel. information: return TraceEventType. information; case LogLevel. verbose: default: return TraceEventType. verbose ;}} public IDisposable BeginScopeImpl (object state) {return new TraceSourceScope (state );}}TraceSourceLogger
        [Fact]        public static void IsEnabledReturnsCorrectValue()        {            // Arrange            var testSwitch = new SourceSwitch("TestSwitch", "Level will be set to warning for this test");            testSwitch.Level = SourceLevels.Warning;            var factory = new LoggerFactory();            var logger = factory.CreateLogger("Test");            // Act            factory.AddTraceSource(testSwitch, new ConsoleTraceListener());            // Assert            Assert.True(logger.IsEnabled(LogLevel.Critical));            Assert.True(logger.IsEnabled(LogLevel.Error));            Assert.True(logger.IsEnabled(LogLevel.Warning));            Assert.False(logger.IsEnabled(LogLevel.Information));            Assert.False(logger.IsEnabled(LogLevel.Verbose));        }        [Theory]        [InlineData(SourceLevels.Warning, SourceLevels.Information, true)]        [InlineData(SourceLevels.Information, SourceLevels.Information, true)]        [InlineData(SourceLevels.Information, SourceLevels.Warning, true)]        [InlineData(SourceLevels.Warning, SourceLevels.Warning, false)]        public static void MultipleLoggers_IsEnabledReturnsCorrectValue(SourceLevels first, SourceLevels second, bool expected)        {            // Arrange            var firstSwitch = new SourceSwitch("FirstSwitch", "First Test Switch");            firstSwitch.Level = first;            var secondSwitch = new SourceSwitch("SecondSwitch", "Second Test Switch");            secondSwitch.Level = second;            var factory = new LoggerFactory();            var logger = factory.CreateLogger("Test");            // Act            factory.AddTraceSource(firstSwitch, new ConsoleTraceListener());            factory.AddTraceSource(secondSwitch, new ConsoleTraceListener());            // Assert            Assert.Equal(expected, logger.IsEnabled(LogLevel.Information));        }    }

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.