Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Serilog to log to the web output directory from appsettings.json?

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?

like image 357
AngryHacker Avatar asked Mar 04 '19 22:03

AngryHacker


People also ask

How do I log into Serilog?

Create a Console Application project in Visual Studio. Install Serilog and its dependencies. Create and configure the Serilog global logger. Integrate the logger into the C# Console Application.


1 Answers

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"
like image 92
Nicholas Blumhardt Avatar answered Oct 05 '22 22:10

Nicholas Blumhardt