1、NLog
导包
包名:NLog.Extensions.Logging
配置文件
创建配置文件,使用默认名字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"
xsi:schemalocation="http://www.nlog-project.org/schemas/nlog.xsd nlog.xsd"
autoreload="true"
throwexceptions="false"
internalloglevel="off" internallogfile="c:\temp\nlog-internal.log">
<!-- optional, add some variables
https://github.com/nlog/nlog/wiki/configuration-file#variables
-->
<!--
<variable name="myvar" value="myvalue"/>
-->
<variable name="fileformat"
value="
${newline}date:${date}
${newline}level:${level}
${newline}machinename:${machinename}
${newline}message:${message}
${newline}appdomain:${appdomain}
${newline}processname:${processname}
${newline}stacktrace: ${stacktrace}
${newline}------------------------------------------------------------" />
<!--see https://github.com/nlog/nlog/wiki/configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<!--
add your targets here
see https://github.com/nlog/nlog/wiki/targets for possible targets.
see https://github.com/nlog/nlog/wiki/layout-renderers for the possible layout renderers.
-->
<!--
write events to a file with the date in the filename.
<target xsi:type="file" name="f" filename="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
<target name="file" xsi:type="file"
filename="${basedir}/logs/${date:format=yyyy-MM}/${shortdate}/${date:format=yyyy-MM-dd HH}.log"
layout="${fileformat}"
maxarchivefiles="24"
archiveabovesize="1024000"
archiveevery="day"/>
</targets>
<rules>
<!-- add your logging rules here -->
<!--
write all events with minimal level of debug (so debug, info, warn, error and fatal, but not trace) to "f"
<logger name="*" minlevel="debug" writeto="f" />
-->
<!--
level example
fatal highest level: important stuff down
error for example application crashes / exceptions.
warn incorrect behavior but the application can continue
info normal behavior like mail sent, user updated profile etc.
debug executed queries, user authenticated, session expired
trace begin method x, end method x etc
-->
<!--
logging 水平分为以下等级“trace<<debug<<info<<warn<<error<<fatal ”,如果我们选择info值,则trace和debug等级的信息不会被输出。
-->
<logger name="*" minlevel="trace" writeto="file"/>
</rules>
</nlog>
封装类
//日志级别:Trace->Debug->Information->Warning->Error->Critical(Fatal),级别包含范围由大到小 ,如 Trace 就包含了所有信息。
public class LogTool
{
private static readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// 五级LOG
/// </summary>
/// <param name="Msg"></param>
public static void Trace(string Msg)
{
_logger.Trace(Msg);
}
/// <summary>
/// 四级LOG
/// </summary>
/// <param name="Msg"></param>
public static void Debug(string Msg)
{
_logger.Debug(Msg);
}
/// <summary>
/// 三级LOG
/// </summary>
/// <param name="Msg"></param>
public static void Info(string Msg)
{
_logger.Info(Msg);
}
/// <summary>
/// 三级LOG
/// </summary>
/// <param name="Msg"></param>
public static void Warning(string Msg)
{
_logger.Warn(Msg);
}
/// <summary>
/// 二级LOG
/// </summary>
/// <param name="Msg"></param>
public static void Error(string Msg)
{
_logger.Error(Msg);
}
/// <summary>
/// 一级LOG
/// </summary>
/// <param name="Msg"></param>
public static void Fatal(string Msg)
{
_logger.Fatal(Msg);
}
}
2、Log4net
导包
包名:LoggerUtils
配置文件
文件名称使用log4net.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net debug="false">
<!-- 将日志信息写入到项目日志文件 -->
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<encoding value="utf-8" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value="D:/Logs/" />
<datePattern value="yyyyMMdd'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="50MB" />
<layout type="log4net.Layout.PatternLayout">
<ConversionPattern value="%date 线程ID:[%thread] 日志级别:%-5level - 描述:%message %newline" />
<!--<ConversionPattern value="%date 线程ID:[%thread] 日志级别:%-5level 相关类:%logger property:[%property{NDC}] - 描述:%message %newline" />-->
</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="%date [%thread] [%-5level] %m %n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="Info" />
<param name="LevelMax" value="Fatal" />
</filter>
</appender>
<appender name="RollingFileAppenderCustomName" type="log4net.Appender.RollingFileAppender">
<encoding value="utf-8" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value="D:/Logs/CustomName/" />
<datePattern value="yyyyMMdd'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="50MB" />
<layout type="log4net.Layout.PatternLayout">
<ConversionPattern value="%date 线程ID:[%thread] 日志级别:%-5level - 描述:%message %newline" />
<!--<ConversionPattern value="%date 线程ID:[%thread] 日志级别:%-5level 相关类:%logger property:[%property{NDC}] - 描述:%message %newline" />-->
</layout>
</appender>
<!--设置根目录,添加appenders并设置默认日志等级 -->
<root>
<level value="All" />
<!--<appender-ref ref="ADONetAppender" />-->
<appender-ref ref="RollingFileAppender"/>
<appender-ref ref="ColoredConsoleAppender"/>
</root>
<logger name="CustomName" additivity="false">
<level value="All" />
<appender-ref ref="RollingFileAppenderCustomName"/>
</logger>
</log4net>
</configuration>
封装类
使用方法:开启和终结日志的使用方法WriteLogStartOrEnd,中间记录统一使用WriteLogToFile
/// <summary>
/// 开启或终结日志
/// </summary>
///<param name="StartOrEnd">开启(START),终结(END)</param>
/// <returns></returns>
public static bool WriteLogStartOrEnd(string StartOrEnd)
{
string strFlag = StartOrEnd.ToUpper();
try
{
switch (strFlag)
{
case "START":
Log4netHelper.Register(@"D:\LogInfo\SendEDIData\");//记录Log,放到本地D盘LogInfo文件夹下的Tea文件夹
Log4netHelper.Instance.Info("===============================================================");
Log4netHelper.Instance.Info("开始执行任务");
break;
case "END":
Log4netHelper.Instance.Info("执行完成");
Log4netHelper.Instance.Info("==============================================================");
break;
default:
Log4netHelper.Instance.Info("开始或结束失败,输入START或END标识有错");
break;
}
return true;
}
catch (Exception ex)
{
//邮件
SendEMailBySite("【编号】" + strFlag + "日志失败", ex.Message.ToString());
return false;
}
}
/// <summary>
/// 记录日志到本地文件中
/// </summary>
/// <param name="Msg">日志内容</param>
/// <returns></returns>
public static bool WriteLogToFile(string Msg)
{
try
{
Log4netHelper.Instance.Info(Msg);
return true;
}
catch (Exception ex)
{
//发邮件
SendEMailBySite("【编号】记录log失败",ex.Message.ToString());
return false;
}
}
标签:Info,LOG,C#,static,Msg,工具,public,string
From: https://www.cnblogs.com/diffknow/p/16653281.html