一、接入Log4net
1.按日期和大小混合分割日志
nuget包安装
log4net
Microsoft.Extensions.Logging.Log4Net.AspNetCore
配置文件
配置文件内容为
xml version="1.0" encoding="utf-8"?> <log4net> <appender name="rollingAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs/" /> <appendToFile value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <rollingStyle value="Composite" /> <datePattern value="yyyyMMdd/"log.log"" /> <maxSizeRollBackups value="20" /> <maximumFileSize value="3MB" /> <staticLogFileName value="false" /> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="ALL" /> <param name="LevelMax" value="FATAL" /> filter> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/> layout> appender> <root> <priority value="ALL"/> <level value="INFO"/> <appender-ref ref="rollingAppender" /> root> log4net>
程序引入,Program.cs文件增加
builder.Logging.AddLog4Net("Configs/log4net.Config"); //Nuget引入: //1.Log4Net //2.Microsoft.Extensions.Logging.Log4Net.AspNetCore builder.Services.AddControllersWithViews();
程序使用
public class HomeController : Controller { private readonly ILogger_logger; public HomeController(ILogger logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation($"{this.GetType()},info,接口访问"); _logger.LogError($"{this.GetType()},error,接口访问错误"); return View(); } }
效果:
2.日志分级独立文件夹显示
上面全部等级的日志信息都显示在同一个文件夹,如果想找error信息,如果日志量大并不好查找,所以把error的独立出来。
增加配置信息
完整配置文件
xml version="1.0" encoding="utf-8"?> <log4net> <appender name="rollingAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs/" /> <appendToFile value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <rollingStyle value="Composite" /> <datePattern value="yyyyMMdd/"log.log"" /> <maxSizeRollBackups value="20" /> <maximumFileSize value="3MB" /> <staticLogFileName value="false" /> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="ALL" /> <param name="LevelMax" value="FATAL" /> filter> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/> layout> appender> <appender name="errorAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs/" /> <appendToFile value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <rollingStyle value="Composite" /> <datePattern value="yyyyMMdd/"error.log"" /> <maxSizeRollBackups value="20" /> <maximumFileSize value="3MB" /> <staticLogFileName value="false" /> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="ERROR" /> <param name="LevelMax" value="ERROR" /> filter> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/> layout> appender> <root> <priority value="ALL"/> <level value="INFO"/> <appender-ref ref="rollingAppender" /> <appender-ref ref="errorAppender" /> root> log4net>
运行,日志打印效果
3.log4net日志写入数据库
这里以log4net写入Mysql为示例
引入Nuget包
MySql.Data
数据库日志表脚本
CREATE TABLE `logs` ( `log_id` bigint NOT NULL AUTO_INCREMENT, `app_name` varchar(100) NOT NULL, `log_date` datetime NOT NULL, `thread` varchar(100) NOT NULL, `level` varchar(50) NOT NULL, `logger` varchar(255) NOT NULL, `message` varchar(1000) NOT NULL, `exception` varchar(2000) NOT NULL, PRIMARY KEY (`log_id`) ) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
增加配置信息
完整配置文件
xml version="1.0" encoding="utf-8"?> <log4net> <appender name="rollingAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs/" /> <appendToFile value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <rollingStyle value="Composite" /> <datePattern value="yyyyMMdd/"log.log"" /> <maxSizeRollBackups value="20" /> <maximumFileSize value="3MB" /> <staticLogFileName value="false" /> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="ALL" /> <param name="LevelMax" value="FATAL" /> filter> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/> layout> appender> <appender name="errorAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs/" /> <appendToFile value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <rollingStyle value="Composite" /> <datePattern value="yyyyMMdd/"error.log"" /> <maxSizeRollBackups value="20" /> <maximumFileSize value="3MB" /> <staticLogFileName value="false" /> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="ERROR" /> <param name="LevelMax" value="ERROR" /> filter> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/> layout> appender> <appender name="mysqlAppender" type="log4net.Appender.AdoNetAppender"> <bufferSize value="0" /> <connectionType value="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" /> <connectionString value="server=127.0.0.1;database=test_db;user=root;pwd=123456;SslMode=none" /> <commandText value="INSERT INTO logs(app_name,log_date, thread, `level`, logger, message, `exception`)VALUES(@app_name,@log_date, @thread,@log_level, @logger, @message, @exception);" /> <parameter> <parameterName value="@app_name" /> <dbType value="String" /> <size value="100" /> <layout type="log4net.Layout.PatternLayout" > <conversionPattern value="api" /> layout> parameter> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="100" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%thread" /> layout> parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> layout> parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> layout> parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="1000" /> <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> <root> <priority value="ALL"/> <level value="INFO"/> <appender-ref ref="rollingAppender" /> <appender-ref ref="errorAppender" /> <appender-ref ref="mysqlAppender" /> root> log4net>
效果
如果是SqlServer
引入Nuget包
System.Data.SqlClient
connectionType写上SqlServer的连接类型
<connectionType value="System.Data.SqlClient.SqlConnection,System.Data.SqlClient, Version=4.6.1.3, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
连接字符串处改成SqlServer的连接字符串即可。
二、接入NLog
1.写文本日志
引入Nuget包
NLog.Web.AspNetCore
配置文件内容
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" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="NLog\all_log.log"> <targets> <target xsi:type="File" name="all_log" fileName="NLog\${shortdate}\${uppercase:${level}}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" archiveFileName="NLog\${shortdate}\${uppercase:${level}}${shortdate}.{####}.log" archiveNumbering="Rolling" archiveAboveSize="10485760" concurrentwrites="true" maxArchiveFiles="100" /> targets> <rules> <logger name="*" minlevel="Trace" writeTo="all_log" /> rules> nlog>
程序引入NLog
程序使用:
结果:
2.过滤日志
有一些组件自带了日志的,像上面的Microsoft.*开头就是.Net Core自带的,我们想屏蔽掉一些dll的日志怎么弄呢
修改配置规则
效果:
3.自定义日志文件名
很多时候我们想把比较重要的功能的日志单独写到一个日志文件方便排查,NLog提供了单独打日志文件的功能
修改配置文件,用一个属性接收,属性由程序端传来:${event-properties:filename}
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" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="NLog\all_log.log"> <targets> <target xsi:type="File" name="all_log" fileName="NLog\${shortdate}\${event-properties:filename}${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" archiveFileName="NLog\${shortdate}\${event-properties:filename}${shortdate}.{####}.log" archiveNumbering="Rolling" archiveAboveSize="10485760" concurrentwrites="true" maxArchiveFiles="100" /> targets> <rules> <logger name="Microsoft.*" minlevel="Trace" final="true" /> <logger name="*" minlevel="Trace" writeTo="all_log" /> rules> nlog>
封装一个LogHelper.cs
public class LogHelper { private static Logger logger= LogManager.GetCurrentClassLogger(); public static void Info(string message,string fileName="INFO") { //把文件名通过属性传输 logger.WithProperty("filename", fileName).Info(message); } public static void Debug(string message, string fileName = "DEBUG") { logger.WithProperty("filename", fileName).Debug(message); } public static void Error(string message, string fileName = "Error") { logger.WithProperty("filename", fileName).Error(message); } public static void Warn(string message, string fileName = "Warn") { logger.WithProperty("filename", fileName).Warn(message); } }
程序调用:
效果:
4.NLog写入数据库
这里以Mysql为例
引入Nuget包
MySql.Data
sql表脚本还是上面Log4net一样。
配置
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" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="NLog\all_log.log"> <targets> <target xsi:type="File" name="all_log" fileName="NLog\${shortdate}\${event-properties:filename}${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" archiveFileName="NLog\${shortdate}\${event-properties:filename}${shortdate}.{####}.log" archiveNumbering="Rolling" archiveAboveSize="10485760" concurrentwrites="true" maxArchiveFiles="100" /> <target name="mysql_log" xsi:type="Database" dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" connectionString="server=127.0.0.1;database=test_db;user=root;pwd=123456;SslMode=none" commandText="INSERT INTO logs(app_name,log_date, thread, `level`, logger, message, `exception`)VALUES(@app_name,@log_date, @thread,@log_level, @logger, @message, @exception);"> <parameter name="@app_name" layout="AspNetCoreNlog" /> <parameter name="@log_date" layout="${date}" /> <parameter name="@thread" layout="${threadid}" /> <parameter name="@log_level" layout="${level}" /> <parameter name="@logger" layout="${logger}" /> <parameter name="@message" layout="${message}" /> <parameter name="@exception" layout="${exception:tostring}" /> target> targets> <rules> <logger name="Microsoft.*" minlevel="Trace" final="true" /> <logger name="*" minlevel="Trace" writeTo="all_log" /> <logger name="*" minlevel="Trace" writeTo="mysql_log" /> rules> nlog>
效果:
如果写SqlServer
引入Nuget包
System.Data.SqlClient
dbProvider="System.Data.SqlClient.SqlConnection, System.Data.SqlClient"
connectionString改为SqlServer的连接字符串即可
5.Log4Net对比NLog
Log4Net对比NLog来说性能相差无几
但是个人推荐用NLog,原因有
1.配置简单
2.可以很方便的自定义日志文件名,这个对于核心模块单独打日志太方便了。