6

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?

AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • I try it using `"pathFormat": "Logs\\log.txt"` and it writes to project directory – ElasticCode Mar 06 '19 at 18:12
  • @WaelAbbas Not when running under IIS Express. Probably with Kestrel it does. – AngryHacker Mar 06 '19 at 18:53
  • Even with `UseKestrel()` I still see the log under project directory, Can you share your startup class and `appsettings.json` just for information, Also .net core ver. – ElasticCode Mar 06 '19 at 19:04
  • @WaelAbbas That's what I am saying. It will store under project directory with Kestrel. And will attempt to store in `c:\program files\iisexpress\` when running under IIS Express – AngryHacker Mar 06 '19 at 19:44
  • in my case it doesn't when running under IIS Express – ElasticCode Mar 07 '19 at 18:09
  • 1
    @WaelAbbas That's probably because you ported your project to .Net Core 2.2 from 2.1 or some earlier version. By default your project would run OutOfProcess. See `AspNetCoreHostingModel` value in your .csproj file. If you start a new project from scratch with .net core 2.2, the `AspNetCoreHostingModel` is `InProcess`, which means that it runs in IIS Express process and thus under that directory. It's inconvenient, but it results in much better throughput when running under IIS in production. – AngryHacker Mar 07 '19 at 18:27

1 Answers1

16

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"
Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101