Asp.net core, a built-Log is, in the console output when selfhost running, not easy to access, if a log rack box, the log persistent, easy to query.
NLog is a free logging framework, specializing in logging framework under the .net platform, this paper illustrates how to use asp.net lower core NLog.
First, by mounting Nuget NLog.Web.AspNetCore NLog.Extensions.Logging and two libraries.
Modify project.json, adding "nlog.config node" in the publishOptions
"publishOptions": {
"include": [
"wwwroot",
"**/*.cshtml",
"appsettings.json",
"web.config",
"nlog.config"
]
}
Add in the StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
// inject HttpContextAccessor to NLog.web
services.AddSingleton();
……
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// add NLog to .net core framework
loggerFactory.AddNLog ();
// add NLog middleware
app.AddNLogWeb();
// Specify NLog profile
env.ConfigureNLog("nlog.config");
……
}
HomeController.cs is a custom log
static Logger Logger = LogManager.GetCurrentClassLogger();
public IActionResult Index()
{
Logger.Info ( "general information log");
Logger.Debug ( "Debug Logs");
Logger.Error ( "Error Log");
Logger.Fatal ( "abnormal log");
Logger.Warn ( "Alert Log");
Logger.Trace ( "trace log");
Logger.Log(NLog.LogLevel.Warn, "Log日志");
try
{
int i = 0;
There are a = 10 / i;
}
catch (Exception exc)
{
// exception log
Logger.Fatal(exc, exc.Message);
}
return View();
}
NLog.config, there are two log records in the C: \ temp, one is all log a record of their own by NLog function of the log. If the log library exceptions, will produce in the c: \ temp under \ internal-nlog.txt,
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Warn"
internalLogFile = "c: \ temp \ internal-nlog.txt">
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
Layout data is to be written in $ contents of the log, according to their needs, choose to save log data.
If you want to save the database log, you can put NLog.config amended as follows:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Warn"
internalLogFile = "c: \ temp \ internal-nlog.txt">
INSERT INTO [dbo].[NLog] (
[MachineName],
[SiteName],
[Logged],
[Level], Wuxi good men and hospital http://www.zzchnk.com/
[UserName],
[Message],
[Logger],
[Properties],
[Host],
[Controller],
[Action],
[Url],
[CallSite],
[Exception]
) VALUES (
@machineName,
@siteName,
@logged,
@level,
@userName,
@message,
@logger,
@properties,
@host,
@controller,
@action,
@url,
@callSite,
@exception
);