如何使Serilog从appsettings.json登录到Web输出目录?

编程入门 行业动态 更新时间:2024-10-25 00:27:48
本文介绍了如何使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 files\iisexpress\log.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 files\iisexpress\log.txt'.

如何将其写入Web应用程序的内容根目录?

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

您可以通过在设置之前更改当前目录来写入相对于Web应用程序的路径记录器:

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%\logs\log.txt"

更多推荐

如何使Serilog从appsettings.json登录到Web输出目录?

本文发布于:2023-11-14 11:34:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目录   appsettings   Serilog   Web   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!