How to get Serilog to log to the web output direct

2020-03-04 07:29发布

I created a new .NET Core web project using Visual Studio and integrated Serilog. It reads settings from the appsettings.json (via .UseSerilog((ctx, config) => { config.ReadFrom.Configuration(ctx.Configuration); })).

In the appsettings.json, the path to write the log is specified at Serilog/WriteTo/Args/pathFormat. If I set that value to log.txt, it will attempt to write the file to `c:\program files\iisexpress\log.txt'.

How can I get it to write to the content root of my web app?

1条回答
▲ chillily
2楼-- · 2020-03-04 08:14

Ideally, you don't want to write log files to the content root of your web app, since these could end up being accessible over the web, which would be a serious security consideration.

The log file path configuration can include environment variables, so something like %TMP%\log.txt, or a path based on %LOCALAPPDATA% etc. is a good option (as long as the web site's worker process has permission to write to the location).

You can write to a path that's relative to your web app by changing the current directory before setting up the logger:

Environment.CurrentDirectory = AppContext.BaseDirectory;

Or, you can combine these approaches and set your own environment variable to do it:

Environment.SetEnvironmentVariable("BASEDIR", AppContext.BaseDirectory);

Thus the following config:

"%BASEDIR%\logs\log.txt"
查看更多
登录 后发表回答