
c#语言使用的日志比较多,比如:Log4、NLog等,今天我就简单随笔记录哈NLog的使用。
1.NLog的安装:
直接在VS编译器中打开程序包管理器,输入Install-Package
NLogin添加进行自己的项目;
VS程序包管理器请查看 http://blog.****.net/doris_d/article/details/46558351
2.安装NLog配置文件:
同上在程序包管理器中加入Install-Package
NLogin.config;
3.添加完成之后,目录大致如下:
4.打开配置文件进行配置
<targets async="true">
<!--
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.
-->
<target xsi:type="File" name="file_info"
fileName="${basedir}/Logs/Info/info_${shortdate}.txt"
layout="${message}"
archiveAboveSize=""
archiveNumbering="Sequence"
concurrentWrites="true"
keepFileOpen="false"
encoding="iso-8859-2"
/>
<target xsi:type="File" name="file_debug"
fileName="${basedir}/Logs/Debug/debug_${shortdate}.txt"
layout="${message}"
archiveAboveSize=""
archiveNumbering="Sequence"
concurrentWrites="true"
keepFileOpen="false"
encoding="iso-8859-2"
/>
<!--
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}" />
-->
</targets>
<rules>
<logger name="*" level="Info" writeTo="file_info"></logger>
<logger name="*" level="Debug" writeTo="file_debug"></logger>
</rules>
注意记录日志有2种方式,同步和异步,只需要再配置targets时候,添加async="true"就为异步,默认为同步。
target备注:type 类型,日志类型有(保存文件、数据库);name 名字和下面role规则对应;fileName 文件保存路径;archiveAboveSize:大小之后会自动添加文件进行保存。
logger备注:level 日志级别(Info、Debug等) writeTo 同上述名字进行匹配。
5.进行简单的测试
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// 写日志
/// </summary>
/// <param name="action"></param>
public static void WriteDeBug(string address, string msg, string path)
{
ExpectionMsg Entity = new ExpectionMsg()
{
Address = address,
Msg = msg,
Path = path
};
logger.Debug(Entity.ToString());
}
6.在config对应的文件中查找文件就好了。