1.NuGet安装NLog
2.添加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"
throwConfigExceptions="true"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<targets>
<!-- 1.将日志写入文件-->
<!-- 单文件 10MB -->
<target name="DeBug_File" xsi:type="File"
archiveFileName="${currentdir}/logs/DeBug_${shortdate}.{##}.log"
archiveAboveSize="10485760"
concurrentWrites="true"
fileName="${currentdir}/logs/DeBug_${shortdate}.log"
layout="${date}_${processid}_${threadid} ${level:uppercase=true} ${event-context:item=Action} ${message} ${event-context:item=Amount} ${stacktrace}"/>
<!-- 2.将日志消息写入数据库-->
<target name="database" xsi:type="Database" connectionstring="Server=47.104.11.154;User ID=sa;Password=sa@2008;database=OeeIot;">
<commandText>
insert into NLogInfo([Date],[origin],[Level],[Message]) values (getdate(), @origin, @logLevel, @message);
</commandText>
日志来源
<parameter name="@origin" layout="${callsite}" />
日志等级
<parameter name="@logLevel" layout="${level}" />
日志消息
<parameter name="@message" layout="${message}" />
</target>
<!-- 3.将日志消息写入Visual Studio输出-->
<target name="debugger" xsi:type="Debugger" layout="NLog: ${date:format=yyyy-MM-dd HH\:mm\:ss} | ${level:uppercase=true:padding=-5} | ${message}" />
<!-- 4.将日志消息写入控制台输出-->
<target name="console" xsi:type="Console" layout="NLog: ${date:format=yyyy-MM-dd HH\:mm\:ss} | ${level:uppercase=true:padding=-5} | ${message}"/>
<target name="CoreLog"
xsi:type="AsyncWrapper"
queueLimit="5000"
overflowAction="Discard">
<target xsi:type="File"
fileName="${currentdir}/logs/Hello_${shortdate}.log"
archiveFileName="${currentdir}/logs/Hello_${shortdate}.{##}.log"
archiveAboveSize="1024"
concurrentWrites="true"
layout="${date}_${processid}_${threadid} ${level:uppercase=true} ${event-context:item=Action} ${message} ${event-context:item=Amount} ${stacktrace}" />
</target>
</targets>
<rules>
<logger name="DeBug_NLog" minlevel="DeBug" writeTo="DeBug_File" />
<logger name="*" writeTo="database" />
<logger name="*" minlevel="Info" writeTo="debugger,console" />
<logger name="*" minlevel="Info" writeTo="CoreLog" />
</rules>
</nlog>
3.数据库建表
创表语句
CREATE TABLE [dbo].[NLogInfo](
[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]
4.代码使用
private static Logger logger = LogManager.GetLogger("DeBug_NLog");
logger.Info("服务端启动");
数据库效果截图
文本Log效果截图