前面做的项目都是用的log4或者用个文件类写入文件中记录日志,这个nlog用着很方便,同时也有net core的版本,一步一步操作吧
1,nuget 中找到nlog并下载安装,注意框架版本,也可以去官网下载 :https://nlog-project.org/
2,安装ok后直接上代码
public sealed class Log
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
public static void Trace(string strMsg)
{
_logger.Trace(strMsg);
}
//有很多重载,可以看提示
public static void Trace(Exception e,string strMsg)
{
_logger.Trace(e,strMsg);
}
public static void Debug(string strMsg)
{
_logger.Debug(strMsg);
}
public static void Info(string strMsg)
{
_logger.Info(strMsg);
}
public static void Warn(string strMsg)
{
_logger.Warn(strMsg);
}
public static void Warn(Exception e)
{
_logger.Warn(e);
}
public static void Warn(Exception e,string strMsg)
{
_logger.Warn(e,strMsg);
}
public static void Error(string strMsg)
{
_logger.Error(strMsg);
}
public static void Error(Exception e, string strMsg)
{
_logger.Error(strMsg);
}
public static void Error(Exception e)
{
_logger.Error(e);
}
public static void Fatal(string strMsg)
{
_logger.Fatal(strMsg);
}
}
2,修改 Nlog.config 的文件,不修改有默认的格式和存储方式
2.1 可以通过文件方式记录,配置文件如下
当然格式化的值有很多,可以查看官方文档
<?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">
<variable name="fileFormat"
value="
${newline}date: ${date}
${newline}level: ${level}
${newline}logger: ${logger}
${newline}machinename: ${machinename}
${newline}message: ${message}
${newline}------------------------------------------------------------" />
<targets> <!-- async="true" 使用异步确保程序退出,日志写完-->
<target name="logfile"
xsi:type="File"
maxArchiveFiles="1"
layout="${fileFormat}"
archiveAboveSize="102400000"
fileName="${basedir}/Logs/${date:format=yyyy-MM}/${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
<logger name="*" minlevel="Trace" writeTo="file"/> <!--写入到文件-->
</rules>
</nlog>
2.2 执行sql记录到数据库中,配置如下
<?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="Trace" internalLogFile="Nlog.log">
<variable name="variable1"
value="
${newline} date: ${date}
${newline}level: ${level}
${newline}logger: ${logger}
${newline}machinename: ${machinename}
${newline}message: ${message}
${newline}appdomain: ${appdomain}
${newline}assembly-version: ${assembly-version}
${newline}basedir: ${basedir}
${newline}callsite: ${callsite}
${newline}callsite-linenumber: ${callsite-linenumber}
${newline}counter: ${counter}
${newline}nlogdir: ${nlogdir}
${newline}processid: ${processid}
${newline}processname: ${processname}
${newline}specialfolder: ${specialfolder}
${newline}stacktrace: ${stacktrace}${newline}" />
<targets>
<!-- <target name="log_file"
xsi:type="File"
fileName="${basedir}/LogInformation/${level}_${shortdate}.txt"
layout="${variable1}" />-->
<target
name="log_database"
xsi:type="Database"
connectionString="Data Source=.;Initial Catalog=localtext;Persist Security Info=True;User ID=sa;Password=">
<commandText>
insert into NLogInfo([Date],[origin],[Level],[Message],[Detail]) values (getdate(), @origin, @logLevel, @message,@detail);
</commandText>
<!--日志来源-->
<parameter name="@origin" layout="${callsite}" />
<!--日志等级-->
<parameter name="@logLevel" layout="${level}" />
<!--日志消息-->
<parameter name="@message" layout="${message}" />
<!--引用variable1信息-->
<parameter name="@detail" layout="${variable1}" />
</target>
</targets>
<rules>
<!--<logger name="*" writeTo="log_file" />-->
<logger name="*" writeTo="log_database" />
</rules>
</nlog>
NLogInfo的表结构创建脚本也给出来:
CREATE TABLE [dbo].[NLogInfo2](
[LogId] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[Origin] [nvarchar](100) NULL,
[Level] [nvarchar](50) NULL,
[Message] [nvarchar](max) NULL,
[Detail] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
3,运行测试
class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始 ...");
try
{
throw new Exception("测试错误");
}
catch (Exception e)
{
for (int i = 0; i < 10; i++)
{
Log.Error(e.Message);
Console.WriteLine($"执行了{i + 1}条记录 ...");
}
}
Console.ReadKey();
}
}
3.1 执行到数据库中的结果
3.2.执行到文件中的结果
ok,写到这里,欢迎指教!