如何让 Serilog 从 appsettings.json 登录到 web 输出目录? [英] How to get Serilog to log to the web output directory from appsettings.json?

查看:24
本文介绍了如何让 Serilog 从 appsettings.json 登录到 web 输出目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Visual Studio 和集成的 Serilog 创建了一个新的 .NET Core Web 项目.它从 appsettings.json 读取设置(通过 .UseSerilog((ctx, config) => { config.ReadFrom.Configuration(ctx.Configuration); })).

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); })).

在 appsettings.json 中,写入日志的路径在 Serilog/WriteTo/Args/pathFormat 中指定.如果我将该值设置为 log.txt,它会尝试将文件写入 `c:program filesiisexpresslog.txt'.

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 filesiisexpresslog.txt'.

我怎样才能让它写入我的网络应用程序的内容根目录?

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

推荐答案

理想情况下,您希望将日志文件写入 Web 应用程序的内容根目录,因为这些文件可能最终被可通过网络访问,这将是一个严重的安全考虑.

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.

日志文件路径配置可以包含环境变量,比如%TMP%log.txt,或者基于%LOCALAPPDATA%等的路径是一个不错的选择(只要网站的工作进程有权写入该位置).

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);

因此如下配置:

"%BASEDIR%logslog.txt"

这篇关于如何让 Serilog 从 appsettings.json 登录到 web 输出目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆