首先使用Nugut安装NLog, NLog.Extensions.Logging,using NLog.Web,并且加上配置文件 ”nlog.config“,配置文件内容网上都可以百度的到。这是我自己的:
创建表:
CREATE TABLE `sys_log` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Account` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`ActionType` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`Level` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`Message` longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
`Date` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`Id`) USING BTREE,
UNIQUE INDEX `Id_UNIQUE`(`Id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
配置config文件
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="true"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
layout="${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
layout="${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
INSERT INTO lifeHome.sys_log (Account,ActionType,Level,Message,Date) Values(@Account,@ActionType,@Level,@Message,@Date)
因为之前一直无法将日志写入数据库,于是百度了好久,将”throwExceptions“设置为true,部署在生产环境建议改为false,这样就可以调试看到错误了,我的原因是sql错误。
之后在Startup.cs里面加上如下代码:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
{
//加载Nlog
loggerFactory.AddNLog();
//加载配置文件
env.ConfigureNLog("nlog.config");
//读取数据库连接
NLog.LogManager.Configuration.Variables["ConnectionStrings"]=_configuration.GetConnectionString("connection");
);
});
}
然后在Program.cs里面写上
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup
. Build();
然后使用过滤器
///
/// 全局异常过滤
///
public class ExceptionFilter : Attribute,IExceptionFilter
{
private readonly ILogger logger;
public ExceptionFilter()
{
logger = LogManager.GetCurrentClassLogger();
}
public void OnException(ExceptionContext context)
{
//如果异常未处理
if(context.ExceptionHandled==false)
{
LogEventInfo lei = new LogEventInfo();
lei.Level = LogLevel.Error;
lei.Properties["Account"] = "1";
lei.Properties["Date"] =DateTime.Now;
lei.Properties["ActionType"] = "1";
lei.Properties["Level"] = "1";
lei.Properties["Message"] = "1";
logger.Log(lei);
//异常已处理
context.ExceptionHandled = true;
}
}
}
数据可以记录到数据库,但是使用简单写法如: logger.Error("12344")还未成功