ASP.NET WebApi project framework construction (4): log management of log4net

I. Introduction

In the process of project development, logging is an indispensable part, which can help us locate abnormalities, analyze the causes of errors and other functions. Log4net is a very good open source logging component under .Net. log4net is very powerful for logging. It can divide the log into different levels and output it to different media in different formats. This article mainly introduces the log processing mechanism added to the projects that have been created in the previous articles.

Second, install and use log4net

1. Use nuget to install log4net

 

The usage of 2.log4net is similar to the following code:

        [Route("log4")]
        [HttpGet]
        public IHttpActionResult Log()
        {
            // Generate an Ilog object through LogManager's static method GetLogger 
            ILog log = LogManager.GetLogger ( typeof (IndexController)); // The following is the log processing 
            log.Debug ( " Test debug " , new Exception ( " debug exception " ));
            log.info ( " Test Info " , new new Exception ( " Info anomaly " ));
            log.Warn ( " Test Warn " , new Exception ( " Warn Exception " ));
            log.Error("测试Error", new Exception("Error异常"));
            log.Fatal ( " Test Fatal " , new Exception ( " Fatal exception " ));
             return Ok ( " Already written to the log " );

        }

3. Run the project, the browser calls the request

Three, decouple Ilog objects through autofac

1. We use autofac Module to register the log4net component, create a new Module folder under the AutoFac directory of the project, and create a new LoggingModule class

 public class LoggingModule : Autofac.Module
    {
        private static void InjectLoggerProperties(object instance)
        {
            var instanceType = instance.GetType();

            // Get all the injectable properties to set.
            // If you wanted to ensure the properties were only UNSET properties,
            // here's where you'd do it.
            var properties = instanceType
              .GetProperties(BindingFlags.Public | BindingFlags.Instance)
              .Where(p => p.PropertyType == typeof(ILog) && p.CanWrite && p.GetIndexParameters().Length == 0);

            // Set the properties located.
            foreach (var propToSet in properties)
            {
                propToSet.SetValue(instance, LogManager.GetLogger(instanceType), null);
            }
        }

        private static void OnComponentPreparing(object sender, PreparingEventArgs e)
        {
            e.Parameters = e.Parameters.Union(
              new[]
              {
        new ResolvedParameter(
            (p, i) => p.ParameterType == typeof (ILog),
            (p, i) => LogManager.GetLogger(p.Member.DeclaringType)
        ),
              });
        }

        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
        {
            registration.Preparing += OnComponentPreparing;

            // Handle properties.
            registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
        }
    }

This code is provided on the official website of autofac, reference address: http://autofaccn.readthedocs.io/en/latest/examples/log4net.html?highlight=module

 2. Register the module under ContainerBuilerCommon

 public static IContainer GetWebApiContainer()
        {
            var builder = new ContainerBuilder ();
             // Register all controllers of webapi 
            builder.RegisterApiControllers (Assembly.GetExecutingAssembly ());
             // Register a component for testing. 
            builder.RegisterType <Person> ();
             // Register log component 
            builder.RegisterModule <LoggingModule> ();
             return builder.Build ();
        }

3. The controller injects Ilog through the constructor

        private ILog _log;
        public IndexController(ILog log, Person person)
        {
            _person = person;
            _log = log;
        }

4. New get request

        [Route("autolog4")]
        [HttpGet]
        public IHttpActionResult AutoLog()
        {
            // Generate an 
            Ilog object through LogManager's static method GetLogger_log.Debug ( " test debug " , new Exception ( " debug exception " ));
            _log.Info ( " Test Info " , new new Exception ( " Info anomaly " ));
            _log.Warn ( " Test Warn " , new Exception ( " Warn Exception " ));
            _log.Error("测试Error", new Exception("Error异常"));
            _log.Fatal ( " Test Fatal " , new Exception ( " Fatal exception " ));
             return Ok ( " Already written to the log " );

        }

5. Now use the get method of the postman tool to access the interface after compiling the program: http: // localhost: xxx / api / autolog4, the program is running normally. But now the log is not written to a file, database or sent to e-mail, nor is it output to the console. This is the benefit of log4net's design. In the program, you only deal with log processing, such as calling ILog's Debug (), Info (), Warn (), Error (), Fatal (). As for the mechanism of log processing (Such as writing files, writing to the database, etc.) is controlled by another process, namely the log4net configuration file. If there is no log4net configuration file in the program, the program can also run normally.

Four, configure Log4net

1. Create a new Log4net.config, the code is as follows

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    </configSections>

    <system.web>
        <compilation debug="true" targetFramework="4.5.2" />
        <httpRuntime targetFramework="4.5.2" />
    </system.web>
<log4net>
    <!-Error log :: Record error log->
    <!-Split log files one by one by date->
    <!-appender defines the log output method and writes the log to the file in the form of a rollback file. ->
    <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
        <!-Save path: When the following path project starts, log and logError files are automatically created in the C drive->
        <file value="log/error/error_" />
        <!-If you want to add a path to this project, just remove C: \\ and only set log \\ LogError to create files by default during project startup->
        <appendToFile value="true"/>
        <!-How to generate multiple log files (date [Date], file size [Size], mixed [Composite])->
        <rollingStyle value="Date"/>
        <!-This is a folder created by date->
        <datePattern value="yyyy-MM-dd'.log'"/>
        <!-Whether it is only written to one file->
        <staticLogFileName value="false"/>
        <!-After the number of retained log files exceeds this number, it will be automatically deleted before it seems to be valid only when split by Size. Value = " -1 " is unlimited number of files->
        <param name="MaxSizeRollBackups" value="100"/>
        <!-The size of each file. Only used in mixed mode and file size mode. After exceeding the size, a positive integer is automatically added after all file names to rename, the earliest number with the largest number is written. Available units: KB | MB | GB. Do not use decimals, otherwise it will always write to the current log->
        <maximumFileSize value="50M" />
        <!-layout controls the output format of Appender, it can also be xml An Appender can only be a layout->
        <layout type="log4net.Layout.PatternLayout">
            <!-Text description at the end of each log->
            <!-Output format template->
            <!-<param name = " ConversionPattern "   value = " Recording time:% date Thread ID: [% thread] Log level:% -5level Record class:% logger    
        Operator ID:% property {Operator} Operation type:% property {Action}% n current machine name:% property% n current machine name and login user:% username% n  
        Record location: % location% n Message description:% property {Message}% n Exception:% exception% n Message:% message% newline% n% n " />->

            <- Example:! 2008 - 03 - 26 is  13 is : 42 is : 32 , 111 [ 10 ] the INFO Log4NetDemo.MainClass [( null )] - info ->
            <!-<conversionPattern value = " % newline% n recording time:% date% n thread ID: [% thread]% n log level:% -5level% n error description:% message% newline% n " />- ->
            <conversionPattern value = " % n =========== 
                                  % n 【Log level】%- 5level
                                   % n 【Record time】% date
                                   % n 【Execution time】 [% r] Millisecond
                                   % n 【Error file 】% F
                                   % n [Error line number]% L
                                   % n [Error class]% logger property [% property {NDC}]
                                   % n [Error description]% message
                                   % n [Error details]% newline " />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter,log4net">
            <levelMin value="ERROR" />
            <levelMax value="FATAL" />
        </filter>
    </appender>

    <!-DEBUG ::: Record DEBUG log->
    <!-Split log files one by one by date->
    <!-appender defines the log output method and writes the log to the file in the form of a rollback file. ->
    <appender name="DebugAppender" type="log4net.Appender.RollingFileAppender">
        <!-Save path: When the following path project starts, log and logError files are automatically created in the C drive->
        <file value="log/debug/debug_" />
        <!-If you want to add a path to this project, just remove C: \\ and only set log \\ LogError to create files by default during project startup->
        <appendToFile value="true"/>
        <!-How to generate multiple log files (date [Date], file size [Size], mixed [Composite])->
        <rollingStyle value="Date"/>
        <!-This is a folder created by date->
        <datePattern value="yyyy-MM-dd'.log'"/>
        <!-Whether it is only written to one file->
        <staticLogFileName value="false"/>
        <!-After the number of retained log files exceeds this number, it will be automatically deleted before it seems to be valid only when split by Size. Value = " -1 " is unlimited number of files->
        <param name="MaxSizeRollBackups" value="100"/>
        <!-The size of each file. Only used in mixed mode and file size mode. After exceeding the size, a positive integer is automatically added after all file names to rename, the earliest number with the largest number is written. Available units: KB | MB | GB. Do not use decimals, otherwise it will always write to the current log->
        <maximumFileSize value="50M" />
        <!-layout controls the output format of Appender, it can also be xml An Appender can only be a layout->
        <layout type="log4net.Layout.PatternLayout">
            <!-Text description at the end of each log->
            <!-Output format template->
            <!-<param name = " ConversionPattern "   value = " Recording time:% date Thread ID: [% thread] Log level:% -5level Record class:% logger    
        Operator ID:% property {Operator} Operation type:% property {Action}% n current machine name:% property% n current machine name and login user:% username% n  
        Record location: % location% n Message description:% property {Message}% n Exception:% exception% n Message:% message% newline% n% n " />->

            <- Example:! 2008 - 03 - 26 is  13 is : 42 is : 32 , 111 [ 10 ] the INFO Log4NetDemo.MainClass [( null )] - info ->
            <!-<conversionPattern value = " % newline% n recording time:% date% n thread ID: [% thread]% n log level:% -5level% n error description:% message% newline% n " />- ->
            <conversionPattern value = " % n ========== 
                                  % n 【Log level】%- 2level
                                   % n 【Record time】% date
                                   % n 【Execution time】 [% r] Millisecond
                                   % n [debug file 】% F
                                   % n [debug line number]% L
                                   % n [debug class]% logger property [% property {NDC}]
                                   % n [debug description]% message " />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter,log4net">
            <levelMin value="DEBUG" />
            <levelMax value="WARN" />
        </filter>
    </appender>
    <!--Set root logger level to DEBUG and its only appender to A1-->
    <root>
        <!-Control level, from low to high: ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF->
        <level value="ALL" />
        <appender-ref ref="DebugAppender" />
        <appender-ref ref="ErrorAppender" />
    </root>
</log4net>
</configuration>

Add the following code to the AssemblyInfo.cs file under 2.properties:

[assembly: XmlConfigurator(Watch = true, ConfigFile = "Log4Net.config")]

3. Run the program and call the log request. Log4net will generate a log file in the log folder under the project home directory

 

 

 

DEBUG log:

 

ERROR log:

 

Guess you like

Origin www.cnblogs.com/huguodong/p/12754808.html