. NET Core logs [4]: Write logs into EventLog and coreeventlog

Source: Internet
Author: User

. NET Core logs [4]: Write logs into EventLog and coreeventlog

Windows-oriented programmers should not be unfamiliar with Event Log, so that many people refer to the Log, the first thing they think of is EventLog. EventLog not only records the logs of various events in the Windows system, but our applications can also use the provided API to write log messages to EventLog. APIS related to EventLog are defined in the System. Diagnostics. EventLog type. We can not only use it to read, write, and delete logs, but also use it to create and delete Event sources .. NET Core's log model uses eventlogger to integrate with EventLog. However, eventlogger uses an abstract EventLog. This article has been synchronized to ASP. NET Core framework secrets.]

 

Directory
1. Abstract EventLog
Ii. eventlogger
3. eventloggerprovider

1. Abstract EventLog

Eventlogger is defined in the NuGet package "Microsoft. Extensions. Logging. EventLog. For the current version, the NuGet package only supports. NET Framework applications. In other words, eventlogger only supports Windows EventLog. However, the log model abstracts EventLog-related operations through an interface.

ConsoleLogger uses the IConsole interface to abstract the consoles of different platforms. eventlogger uses the abstract EventLog to be expressed through the IEventLog interface. As shown in the following code snippet, The IEventLog interface only defines a unique method WriteEntry to write logs. The provided parameters are used to specify the message and type of the log), event ID (eventID) and category (category ). To avoid a single log containing too much content, the IEventLog interface defines a read-only attribute MaxMessageSize to set the maximum length allowed by the log message text.

   1: public interface IEventLog
   2: {
   3:     void WriteEntry(string message, EventLogEntryType type, int eventID, short category);
   4:     int MaxMessageSize { get; }
   5: }
   6:  
   7: public enum EventLogEntryType
   8: {
   9:     Error           = 1, 
  10:     Warning         = 2,
  11:     Information     = 4,
  12:     SuccessAudit    = 8 
  13:     FailureAudit    = 16
  14: }

All logs recorded by EventLog have a type indicated by enumeration EventLogEntryType, which is equivalent to the log level. For the five types defined in this enumeration, Error, Warning, and Information have the same meaning as the log levels with the same name, while SuccessAudit and FailureAudit represent the logs for the "Audit (Audit)" event, they represent reviews of "successful events" and "failed events" respectively. When eventlogger writes logs using EventLog, it converts the specified log level to the log type of EventLog. The conversion rule is simple: the log levels for Error, Warning, and Information are converted to EventLog types with the same name, while those for other levels are converted to Information types.

WindowsEventLog with the following definitions is the default implementer for the IEventLog interface. A WindowsEventLog is actually an encapsulation of an EventLog object, which is represented by the DiagnosticsEventLog attribute. This encapsulated EventLog object is created in the constructor by specifying the log name (logName), machine name (machineName), and Event Source name (sourceName) of the corresponding parameter. In the implemented WriteEntry method, the WriteEntry of this EventLog is called directly to write logs. The MaxMessageSize attribute of WindowsEventLog returns a constant of 31839. The log message text cannot exceed this length.

   1: public class WindowsEventLog : IEventLog
   2: {
   3:     private const int MaximumMessageSize = 31839;
   4:  
   5:     public int MaxMessageSize
   6:     {
   7:         get { return MaximumMessageSize; }
   8:     }
   9:  
  10:     public System.Diagnostics.EventLog DiagnosticsEventLog { get; }
  11:  
  12:     public WindowsEventLog(string logName, string machineName, string sourceName)
  13:     {
  14:         DiagnosticsEventLog = new System.Diagnostics.EventLog(logName, machineName, sourceName);
  15:     }
  16:  
  17:     public void WriteEntry(string message, EventLogEntryType type, int eventID, short category)   
  18:     {
  19:         DiagnosticsEventLog.WriteEntry(message, type, eventID, category);
  20:     }
  21: }
Ii. eventlogger

The log model uses eventlogger to integrate with EventLog. Specifically, an eventlogger is actually an encapsulation of the EventLog object, which is used to write logs to EventLog. The eventlogger type has the following definitions. We can see that it has two constructor functions. Apart from providing the Logger name, one constructor has a parameter of the EventLogSettings type, this encapsulated EventLog object is formally created using the information provided by this parameter.

   1: public class EventLogLogger : ILogger
   2: {
   3:     public EventLogLogger(string name);
   4:     public EventLogLogger(string name, EventLogSettings settings);
   5:  
   6:     public IDisposable BeginScope<TState>(TState state);  
   7:     public bool IsEnabled(LogLevel logLevel);
   8:     public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, 
   9:     Func<TState, Exception, string> formatter);
  10: }
  11:  
  12: public class EventLogSettings
  13: {
  14:     public IEventLog              EventLog { get; set; }
  15:  
  16:     public string                 LogName { get; set; }
  17:     public string                 MachineName { get; set; }
  18:     public string                 SourceName { get; set; } 
  19:  
  20:     public Func<string, LogLevel, bool>     Filter { get; set; }
  21: }

As shown in the code snippet above, we can use the EventLog attribute of the EventLogSettings object to provide eventlogger with a specific EventLog object. If this attribute is Null, eventlogger will use the other three attributes of EventLogSettings (LogName, MatcheName, and SourceName) to create a WindowsEventLog object. In addition to the four attributes related to the creation or provision of EventLog objects, EventLogSettings also has another Func <string, LogLevel, bool> type attribute Filter, which naturally represents the log message Filter.

When eventlogger uses EventLogSettings to create a WindowsEventLog object, if the related attributes (LogName, MatcheName, and SourceName) are not explicitly set in the EventLogSettings object, it uses the predefined default value. Specifically, the default values are "Application" [1], "." (representing the local machine), and "Application ". If we call the first constructor overload, we will actually use these default values to create a WindowsEventLog object. If the name (name parameter) is not specified when the constructor is called, The type name ("eventlogger") is used to name the created Logger.

Eventlogger and DebugLogger do not support the log context range, so its BeginScope <TState> method and returned object are meaningless. The Filter attribute of EventLogSettings returns the Func <string, LogLevel, bool> object to be used by the IsEnabled method. If a delegate object is not explicitly provided, this method always returns True. When the Log method is called, it uses the same method as DebugLogger to format the final Log message text. Therefore, duplicate descriptions of exceptions still exist. Log messages are eventually written to EventLog by calling the WriteEntry method of EventLog. However, before that, the system checks whether the formatted Log message text exceeds the length limited by the MaxMessageSize attribute. If the length exceeds the limit, log messages are split and written to EventLog multiple times.

3. eventloggerprovider

Eventlogger is provided by the corresponding EventLogLoggerProvider. The following code shows the complete definition of this type. We can call the following three extension methods AddEventLog to create an eventloggerprovider and register it on the specified LoggerFactory, you can use this method to specify the EventLogSettings object used to provide or assist in creating EventLog and the lowest log level.

   1: public class EventLogLoggerProvider : ILoggerProvider, IDisposable
   2: {
   3:     private readonly EventLogSettings _settings;
   4:     public EventLogLoggerProvider() : this(null)
   5:     {}
   6:  
   7:     public EventLogLoggerProvider(EventLogSettings settings)
   8:     {
   9:         _settings = settings;
  10:     }
  11:  
  12:     public ILogger CreateLogger(string name)
  13:     {
  14:         return new EventLogLogger(name, _settings ?? new EventLogSettings());
  15:     }
  16:  
  17:     public void Dispose()
  18:     {}
  19: }
  20:  
  21: public static class EventLoggerFactoryExtensions
  22: {
  23:     public static ILoggerFactory AddEventLog(this ILoggerFactory factory);
  24:     public static ILoggerFactory AddEventLog(this ILoggerFactory factory, EventLogSettings settings);
  25:     public static ILoggerFactory AddEventLog(this ILoggerFactory factory, LogLevel minLevel);
  26: }

We also use a simple console application to demonstrate log records for EventLog. We prefer to create an empty console application and add the required dependencies to project. json. Because the log records for EventLog are only applicable to. NET Framework applications, we only define a Framework for the application for. NET Framework 4.6.1 (net461.

   1: {
   2:   ...
   3:   "dependencies": {
   4:     "Microsoft.Extensions.DependencyInjection"    : "1.0.0",
   5:     "Microsoft.Extensions.Logging"                : "1.0.0",
   6:     "Microsoft.Extensions.Logging.EventLog"       : "1.0.0"
   7:   },
   8:  
   9:    "frameworks": {
  10:     "net461": {
  11:       "frameworkAssemblies": {
  12:         "System.Runtime": {
  13:           "type": "build"
  14:         }
  15:       }
  16:     }
  17:   }
  18: }

We have compiled the following program to complete the log record for EventLog. As shown in the following code snippet, we first create an Event Source named "Demo" for the logs to be written (it generally represents the name of the application or service to which the logs are written ). Next, we create a LoggerFactory object using dependency injection, and call the extension method AddEventLog to create an EventLoggerProvider object and register it with LoggerFactory. When we call this AddEventLog method, we specify an EventLogSettings object and set its SourceName attribute to "Demo ". We finally use this LoggerFactory object to create the corresponding Logger and use it to write a log with the Error level.

   1: public class Program
   2: {
   3:     public static void Main(string[] args)
   4:     {
   5:         if(!EventLog.SourceExists("Demo"))
   6:         {
   7:             EventLog.CreateEventSource("Demo", "Application");
   8:         }
   9:  
  10:         new ServiceCollection()
  11:             .AddLogging()
  12:             .BuildServiceProvider()
  13:             .GetService<ILoggerFactory>()
  14:             .AddEventLog(new EventLogSettings { SourceName = "Demo" })
  15:             .CreateLogger<Program>()
16:. LogError ("Database connection failed (Database: {Database}, Username: {User})", "TestDb", "sa ");
  17:     }
  18: }

Because the above program involves viewing and creating Event Source, it must be run properly with the administrator privilege. After the program runs, view the Event Viewer. We will see the log message written. As shown in figure 10, because the EventLogSettings provided when we call the extension method AddEventLog does not explicitly specify the EventLog name, our logs will be written to the Application EventLog by default.

[1] Windows provides three eventlogs by default, namely Application, System, and Security. logs generated by applications can only be written to Application and System logs, and Security logs are read-only. In addition to these three eventlogs, we can also create independent eventlogs for the application.

. NET Core logs [1]: logs are recorded in a unified mode.
. NET Core logs [2]: Write logs to the console
. NET Core logs [3]: Write logs to the Debug window
. NET Core logs [4]: Using EventLog to write logs
. NET Core logs [5]: Use TraceSource to write logs

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.