.net core 3.1 新增log4net 和 NLog

.net 中用的比较多的日志是log4net 和 NLog,这次两个都尝试一次

log4net 我直接在webapi中添加,NLog 单独创建了一个项目,方便业务逻辑层或其他地方调用

log4net的添加和调用

首先在webapi安装 log4net ,然后新增 log4net.config 以及 LogHelper.cs 两个文件

log4net.config 源码如下:

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

<log4net>
<!-- 信息日志类 -->
<logger name="loginfo">
<level value="ALL" />
<appender-ref ref="AdoNetAppender" />
<appender-ref ref="InfoAppender" />
</logger>
<!-- 警告日志类 -->
<logger name="logwarn">
<level value="ALL" />
<appender-ref ref="WarnAppender" />
</logger>
<!-- 错误日志类-->
<logger name="logerror">
<level value="ALL" />
<appender-ref ref="AdoNetAppender" />
<appender-ref ref="ErrorAppender" />
</logger>
<!-- 异常日志类-->
<logger name="logfatal">
<level value="ALL" />
<appender-ref ref="AdoNetAppender" />
<appender-ref ref="FatalAppender" />
</logger>

<!-- 文件保存日志 -->
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<!--日志路径: 兼容相对路径和绝对路径 -->
<param name= "File" value= "Log\info\"/>
<!--是否是向文件中追加日志-->
<param name= "AppendToFile" value= "true"/>
<!--保留天数-->
<param name= "MaxSizeRollBackups" value= "10"/>
<!--日志文件名是否固定不变的-->
<param name= "StaticLogFileName" value= "false"/>
<!--日志文件名格式为:20170112.log-->
<param name= "DatePattern" value= "yyyyMMdd&quot;.log&quot;"/>
<!--日志根据日期滚动-->
<param name= "RollingStyle" value= "Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss.fff} %-5p %m%n" />
</layout>
</appender>

<appender name="WarnAppender" type="log4net.Appender.RollingFileAppender">
<param name= "File" value= "Log\warn\"/>
<param name= "AppendToFile" value= "true"/>
<param name= "MaxSizeRollBackups" value= "10"/>
<param name= "StaticLogFileName" value= "false"/>
<param name= "DatePattern" value= "yyyyMMdd&quot;.log&quot;"/>
<param name= "RollingStyle" value= "Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss.fff} %-5p %m%n" />
</layout>
</appender>

<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
<param name= "File" value= "Log\error\"/>
<param name= "AppendToFile" value= "true"/>
<param name= "MaxSizeRollBackups" value= "10"/>
<param name= "StaticLogFileName" value= "false"/>
<param name= "DatePattern" value= "yyyyMMdd&quot;.log&quot;"/>
<param name= "RollingStyle" value= "Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss.fff} %-5p %m%n" />
</layout>
</appender>

<appender name="FatalAppender" type="log4net.Appender.RollingFileAppender">
<param name= "File" value= "Log\fatal\"/>
<param name= "AppendToFile" value= "true"/>
<param name= "MaxSizeRollBackups" value= "10"/>
<param name= "StaticLogFileName" value= "false"/>
<param name= "DatePattern" value= "yyyyMMdd&quot;.log&quot;"/>
<param name= "RollingStyle" value= "Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss.fff} %-5p %m%n" />
</layout>
</appender>

<!-- 控制台输出日志 -->
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="Info" />
<foreColor value="Green" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n%date{HH:mm:ss.fff} %-5level %m" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="Info" />
<param name="LevelMax" value="Fatal" />
</filter>
</appender>

<!-- 数据库保存 -->
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=.;initial catalog=test_log;integrated security=true" />
<commandText value="INSERT INTO log([userid],[level],[ip],[msg],[exception]) VALUES (@userid,@level,@ip, @msg,@exception)" />
<parameter>
<parameterName value="@userid"/>
<dbType value="Int64"/>
<size value="64"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%X{userid}"/>
</layout>
</parameter>
<parameter>
<parameterName value="@level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@ip" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%X{ip}" />
</layout>
</parameter>
<parameter>
<parameterName value="@msg" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>

</log4net>
</configuration>

 

LogHelper.cs源码如下:

public class LogHelper
{
private const string repositoryName = "NETCoreRepository";
private const string configFile = "log4net.config";
private static ILoggerRepository repository { get; set; }

private static readonly ILog _loginfo =LogManager.GetLogger(repositoryName, "loginfo");
private static readonly ILog _logerror = LogManager.GetLogger(repositoryName, "logerror");
private static readonly ILog _logwarn = LogManager.GetLogger(repositoryName, "logwarn");
private static readonly ILog _logfatal = LogManager.GetLogger(repositoryName, "logfatal");

public static void Configure()
{
repository = LogManager.CreateRepository(repositoryName);
XmlConfigurator.Configure(repository, new FileInfo(configFile));
}

public static void Info(string msg)
{
_loginfo.Info(msg);
}

public static void Warn(string msg)
{
_logwarn.Warn(msg);
}

public static void Error(string msg)
{
_logerror.Error(msg);
}

public static void Fatal(string msg)
{
_logfatal.Fatal(msg);
}

 

最后在Startup.cs文件的ConfigService方法中添加以下代码,读取配置

LogHelper.Configure(); //使用前先配置

 

log4net 就配置好了,需要调用可以执行 

LogHelper.Info("XXX");

在webapi根目录下就会生成Log文件夹,里面分别记录 info warn error fatal 日志文件

 

NLog的新增和调用

首先安装NLog.web.AspNetCore

NLog 也需要两个文件 nlog.config 以及 NLogHelper.cs 

新增项目Summer.Logger,项目下新增NLogHelper.cs (如果不想单独新建logger项目,也可以直接把这两个文件放在要引用的项目下)

NLogHelper.cs 源码如下,只有一行代码:

public class NLogHelper : NLog.Logger
{
public static readonly NLog.Logger logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

}

nlog.config 文件放在要引用的项目根目录下,且属性设置为 “始终复制”

 

 

 

假设在Service项目要引用NLog,先引用Logger项目,并添加nlog.config

 

nlog.config源码如下:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true">
<!-- the targets to write to -->
<targets>
<!-- 输出到文件,这个文件记录所有的日志 -->
<!--<target xsi:type="File" name="allfile" fileName="NLog\LogAll\${shortdate}.htm"
layout="&lt;HR COLOR=red&gt;${longdate}&lt;BR&gt;${logger}&lt;BR&gt;${uppercase:${level}}&lt;BR&gt;${message} ${exception}&lt;HR Size=1&gt;" />-->

<!-- 输出到文件,这个文件记录错误日志 -->
<target xsi:type="File" name="logError" fileName="NLog\LogError\${shortdate}.htm"
layout="&lt;HR COLOR=red&gt;【异常时间】:${date} &lt;BR&gt;【异常级别】:${level:uppercase=true} &lt;BR&gt;${message}&lt;HR Size=1&gt;" />

<!-- 输出到文件,这个文件记录操作日志 -->
<target xsi:type="File" name="logInfo" fileName="NLog\LogInfo\${shortdate}.htm"
layout="&lt;HR COLOR=red&gt;【操作时间】:${date} &lt;BR&gt;【操作级别】:${level:uppercase=true} &lt;BR&gt;${message}&lt;HR Size=1&gt;" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<!--<logger name="*" minlevel="Trace" writeTo="allfile" />-->
<logger name="*" minlevel="Error" writeTo="logError" />
<logger name="*" minlevel="Info" maxLevel="Info" writeTo="logInfo" />
<logger name="Microsoft.*" maxLevel="Info" final="true" />
</rules>
</nlog>

 

引用的代码如下:

NLogHelper.logger.Error("XXX");

在项目运行目录就会生成NLog文件夹,里面记录相关日志

 

以上就是log4net 和NLog 接入.net core 3.1 的方法

posted @ 2020-03-18 21:21  redo  阅读(1264)  评论(0编辑  收藏  举报