.NetCore接入Log4Net

首先接入NuGet包Log4Net

在项目中添加log4net.config文件

Log4Net的级别None>FATAL>ERROR>WARN>INFO>DEBUG>ALL

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <!-- This section contains the log4net configuration settings -->
  <log4net>
    <root>
        <level value="INFO" />
        <appender-ref ref="infoAppender" />
        <appender-ref ref="errorAppender" />
    </root>            
    <appender name="errorAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Logs/Error/" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <staticLogFileName value="false" />
      <datePattern value="error-yyyyMMdd'.log'" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1MB" />
      <threshold value="ERROR" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <appender name="infoAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Logs/Info/" />
      <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>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="Info" />
        <param name="LevelMax" value="Info" />
      </filter>
    </appender>
    <!-- Setup the root category, add the appenders and set the default level -->    
  </log4net>
</configuration>

若要控制显示的层级,可以在Appender中使用Threshold,当级别小于这个将会过滤,或者如下选择控制层级。

<filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="Info" />
        <param name="LevelMax" value="Info" />
      </filter>

在.NetFramework中可以使用LogManger获取相应的Loger,但是在.NetCore需要使用ILoggerRepository,贴一个简易的LogHelper,大家有更好的可以推荐给我!

using log4net;
using log4net.Config;
using log4net.Repository;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace LwccWeightReduction.Helpers
{
    class SimpleLogHelper
    {
        private static ILog logger = null;
        public static void LogInfo(string logstr)
        {
            if (InitLog4net())
                logger.Info(logstr);
        }

        public static void LogInfo(string format, params object[] args)
        {
            if (InitLog4net())
                logger.InfoFormat(format, args);
        }

        public static void LogError(string logstr)
        {
            if (InitLog4net())
                logger.Error(logstr);
        }

        public static void LogError(string format, params object[] args)
        {
            if (InitLog4net())
                logger.ErrorFormat(format, args);
        }

        private static object objlock = new object();//初始化log用的锁
        private static bool InitLog4net()
        {
            if (logger != null)
                return true;
            lock (objlock)
            {
                if (logger == null)
                {
                    ILoggerRepository repository = LogManager.CreateRepository("NETCoreRepository");
                    XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
                    logger = LogManager.GetLogger(repository.Name, "NETCorelog4net");
                    return true;
                }
            }
            return false;
        }
    }
}

有三个小坑:

1.如果在Debug模式下可以生成日志,Release模式下生成不了,可以在LogHelper下的命名空间中添加如下语句:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

2..NetCore打包成exe发布到WinServer上,无法输出日志,但在本机上面可以。可以以管理员方式运行exe即可输出日志。

3.程序发布到LINUX上,使用.sh脚本在任一路径下运行的时候会出现无法记录日志问题。查询原因得知,.Net Core记录Log4的类,记录前会获取ILoggerRepository,读取Config文件的时候,使用的是相对路径,即启动的程序时候的路径—.sh脚本路径。这样就获取不到log4net.config文件,无法记录日志,需要调整路径。

posted @ 2019-03-27 19:08  国-哥  阅读(1409)  评论(0编辑  收藏  举报