C#中使用log4net框架做日志输出

2021-04-11 20:37

阅读:711

标签:logfile   str   prope   using   org   pen   AC   pat   size   

一、用法

1、引入包:https://www.nuget.org/packages/log4net/

2、Main函数 

using System;
using System.IO;
using log4net;
using log4net.Config;

namespace Log4NetDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var repository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
            var log = LogManager.GetLogger("NETCoreRepository", typeof(Program));

            log.Info("this is a info.");
            log.Error("this is an error:", new Exception("this is error."));
            log.Fatal("this is a fatal.");
            log.Warn("this is a warn");
            Console.WriteLine("finish.");
        }
    }
}

3、新建一个log4net.config配置文件,并设置输出到程序目录下。

xml version="1.0" encoding="UTF-8"?>

configuration status="ON">
    log4net>
        appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
            layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
        appender>
        appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
            file value="logs/" />
            appendToFile value="true" />
            rollingStyle value="Composite" />
            staticLogFileName value="false" />
            datePattern value="yyyyMMdd‘.log‘" />
            maxSizeRollBackups value="10" />
            maximumFileSize value="1MB" />
            layout type="log4net.Layout.PatternLayout">
                conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
            layout>
        appender>
        root level="ALL">
            appender-ref ref="ConsoleAppender" />
            appender-ref ref="RollingLogFileAppender" />
        root>
    log4net>
configuration>

4、效果:

技术分享图片

 

C#中使用log4net框架做日志输出

标签:logfile   str   prope   using   org   pen   AC   pat   size   

原文地址:https://www.cnblogs.com/songxingzhu/p/9022435.html


评论


亲,登录后才可以留言!