场景:ASP.NET MVC 6 Web应用程序。
以下是project.json
中导入的软件包:
"Serilog": "2.3.0",
"Serilog.Extensions.Logging": "1.3.1",
"Serilog.Sinks.RollingFile": "3.2.0",
"Serilog.Settings.Configuration": "2.2.0"
这是appsettings
配置
"Serilog": {
"Using": [ "Serilog.Sinks.RollingFile" ],
"MinimumLevel": {
"Default": "Verbose",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore.Identity": "Debug",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"path": "logger-{Date}.log",
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}",
"fileSizeLimitBytes": 16384
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Sample"
}
},
这是Startup
构造函数
var builder = new ConfigurationBuilder()
.SetBasePath( _environment.ContentRootPath )
.AddJsonFile( "appsettings.json", optional: true, reloadOnChange: true )
.AddJsonFile( $"appsettings.{_environment.EnvironmentName}.json", optional: true );
Configuration = builder.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration( Configuration )
.CreateLogger();
在配置方法中我有
loggerFactory.AddConsole();
loggerFactory.AddSerilog();
应该在哪里写文件?可能是与写入权限相关的问题吗?
修改
关注@Sanket建议,但仍然无效。我也切换到红隼,看看它是否在控制台上工作,但仍然没有运气。这就是我所看到的:
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method MyCompany.MyProject.Host.Controllers.HomeController.Index MyCompany.MyProject.Host) with arguments (
(null)) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor[1]
Executing ViewResult, running view at path /Views/Home/Index.cshtml.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action MyCompany.MyProject.Host.Controllers.HomeController.Index (MyCompany.MyProject.Host) in 2614.9118ms
这对我来说非常奇怪,因为我只是在
的索引操作中使用Home Controllerpublic IActionResult Index() {
_logger.LogDebug( "Index in HomeController called!" );
return View();
}
答案 0 :(得分:3)
在启动时,您可以像这样指定滚动文件的路径 -
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "Serilog-{Date}.txt"))
.CreateLogger();
<强>更新强>
在appsettings.json中,将路径参数更改为 pathFormat
"path": "logger-{Date}.log",
到
"pathFormat": "logger-{Date}.log",
将在项目位置创建文件。
请参阅此link
<强> UPDATE2:强>
在Startup构造函数中,像这样更改serilog logger -
这
var logger = new LoggerConfiguration()
.ReadFrom.Configuration( Configuration )
.CreateLogger();
要
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.CreateLogger();