In asp.net core projects added to the local log file through log4net

===============================================

 2020/2/25-stage first edit              ccb_warlock          

 

===============================================

Because of the time before the busy business development projects for the use log4net has been "used", just look at the results to the console when debugging in a while there is no specific mechanism parameters and configuration files get to the bottom.

Happened this time the project schedule was not so nervous, I also have time to complete part of the framework of the log output, the idea of ​​holding "the easier issues first," I do not go first to achieve such a system similar elasticsearch to write the log log first starting implement written to a local file.

Originally written winform when vaguely remember mostly to write to a log file by way of data streams, which also consider whether the log file exists, exceeds the size, how to do so on thread safety, after tests found log4net function package is really very simple.

 


First, add a profile log4net.config

PS. Of course, the configuration file can not be that name, I'm here for the convenience of direct use log4net.config

# Add the following to the log4net.config

<?xml version="1.0" encoding="utf-8"?>

<log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger - %message %newline" />
        </layout>
    </appender>

    <appender name="DebugRollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="/var/tmp/log/myApp/debug/" />
        <appendToFile value="true" />
        <rollingStyle value="Composite" />
        <staticLogFileName value="false" />
        <datePattern value="yyyy-MM-dd'.txt'" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="1MB" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
        </layout>
    </appender>
    
    <appender name="ErrorRollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="/var/tmp/log/myApp/error/" />
        <appendToFile value="true" />
        <rollingStyle value="Composite" />
        <staticLogFileName value="false" />
        <datePattern value="yyyy-MM-dd'.txt'" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="1MB" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter">
            <param name="LevelMin" value="ERROR" />
            <param name="LevelMax" value="FATAL" />
        </filter>
    </appender>

    <root>
        <level value="ALL" />
        <appender-ref ref="ConsoleAppender" />
        <appender-ref ref="DebugRollingFileAppender" />
        <appender-ref ref="ErrorRollingFileAppender" />
    </root>
</log4net>

PS. Wording ( <File value = "/ var / tmp / log / myApp / Debug /" /> ) is equivalent to writing ( <param name = "File" value = "/ var / tmp / log / myApp / Debug / "/> )

 

You can see, DebugRollingFileAppender ErrorRollingFileAppender is to achieve and write local files created configuration, followed by a detailed description of the parameters for which entries.

Parameter description Value range
file Path to the log file is located  
appendToFile Write mode

true. Incremental write

false. overwritten

rollingStyle naming method

Date. Named by date

Size. Named by file size

Composite. Integrated date and file size to name

staticLogFileName File name is variable

true. immutable (static)

false. The variable

datePattern Date format (used to control the scrolling cycle). Suffix .txt if desired, may be added '.txt' behind the content.  
maxSizeRollBackups The maximum number of files within a rolling period -1 indicates no limit to the number
maximumFileSize

The maximum space for each file.

When the log file exceeds the limit, if the number of log files in the rolling period less than the maximum number of files, will create a new file. If equal to the maximum number of files, it will re-write restart from the first file in the rolling cycle

 
conversionPattern Each log format  
filter Filter (to set the type of recording depending on the log)  

 

Then separate out logging format described

<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
parameter description Logogram
%datetime Generates a log record time %d
%thread Log records are generated thread ID %t
%-5level The log level  
%logger The method of generating a class where the log (including assembly)  
%property Attributes  
%message Information log %m
%newline Wrap %n
%L The line number where the log file statement  
%F The log file path statement where (including the file name)  

level: the lowest level of the log, according to the level corresponding to the log record as follows:

 ALL    DEBUG   INFO    WARN    ERROR   FATAL   OFF
•All                        
•DEBUG  •DEBUG                  
•INFO   •INFO   •INFO               
•WARN   •WARN   •WARN   •WARN           
•ERROR  •ERROR  •ERROR  •ERROR  •ERROR      
•FATAL  •FATAL  •FATAL  •FATAL  •FATAL  •FATAL  
•OFF    •OFF    •OFF    •OFF    •OFF    •OFF    •OFF

 


Second, add log4net in the project

My project is asp.net core .net core 2.2-based project created for the added log4net is implemented in program.cs, the specific code as follows:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;

namespace Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        private static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureLogging((context, logging) =>
                {
                    logging.AddLog4Net();
                })
                .UseStartup<Startup>();
    }
}

 

接着后面的程序只要有log输出就会向指定的文件内写日志,例如我在定时任务中添加的日志输出:

using log4net;
using Quartz;

namespace Domain.Jobs
{
    public class ServiceToken : IJob
    {
        private readonly ILog _log = LogManager.GetLogger(typeof(ServiceToken));

        ······
        
        public Task Execute(IJobExecutionContext context)
        {
            var now = DateTimeOffset.Now;
            
            _log.Debug($"{now:yyyy/MM/dd HH:mm:ss.fff}, 执行维护token的任务.");

            // todo
            
            return Task.CompletedTask;
        }
    }
}

 

 


参考资料:

1.http://logging.apache.org/log4net/release/config-examples.html

2.https://stackoverflow.com/questions/8926409/log4net-hierarchy-and-logging-levels?r=SearchResults

 

 

 

Guess you like

Origin www.cnblogs.com/straycats/p/12359787.html