我发现了serilog(.net的结构化日志),并发现了很多优点.但是我遇到了一些问题.我有4个项目,一个是web,一个是基础设施,另外两个是windows服务,我想声明一次serilog配置并多次使用它.而且我也希望将它与依赖注入一起使用.我已经在网上搜索了三天了,但我没有找到任何有用的东西,请一些人帮助我.
例如,我希望这个类成为我的日志类.
public interface IMyLogger
{
void Information(string message, object[] parameters);
}
public class MyLogger : IMyLogger
{
public MyLogger()
{
}
public void Information(string message, object[] parameters)
{
Log.Information("LogType : {LogType} - Operation : {Operation}", parameters);
}
}
public class UserClass
{
private readonly IMyLogger _myLogger;
public UserClass(IMyLogger myLogger)
{
_myLogger = myLogger;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我不知道应该把这行代码放在哪里:
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
Tnx提前.
我正在使用 Serilog - RollingFile Sink,但它将所有数据存储在一个文件中一天。在我的应用程序中,一天写入 1 GB 日志。所以我想根据日期和大小滚动日志文件。
如何配置 RollingFile Sink 以根据日期和大小滚动文件?
我的解决方案有一个主记录器,它被定义为
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.LiterateConsole(LogEventLevel.Verbose)
.WriteTo.RollingFile($"{appLogDir}{Path.DirectorySeparatorChar}logs{Path.DirectorySeparatorChar}V-RPi-{{Date}}.log")
.WriteTo.RollingFile($"{appLogDir}{Path.DirectorySeparatorChar}logs-warnings{Path.DirectorySeparatorChar}V-RPi-{{Date}}.log", LogEventLevel.Warning)
.WriteTo.File($"{appLogDir}{Path.DirectorySeparatorChar}recent-log.log", fileSizeLimitBytes: 134217728, restrictedToMinimumLevel: LogEventLevel.Verbose)
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
我想创建两个单独的记录器来记录两个类实例中的内容。我已将它们定义如下。它位于与主项目不同的程序集中。
private ILogger comRespLog;
public **constructor**(string name)
{
comRespLog = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.RollingFile($"{appLogDir}{Path.DirectorySeparatorChar}logs-CommandResponse-{Name}{Path.DirectorySeparatorChar}V-RPi-{{Date}}.log")
.CreateLogger();
}
Run Code Online (Sandbox Code Playgroud)
我没有收到构建错误,但我在运行时收到了这个错误。
方法未找到:'Serilog.LoggerConfiguration Serilog.RollingFileLoggerConfigurationExtensions.RollingFile(Serilog.Configuration.LoggerSinkConfiguration, System.String, Serilog.Events.LogEventLevel, System.String, System.IFormatProvider, System.Nullable
1<Int64>, System.Nullable1, Serilog.Core.LoggingLevelSwitch, Boolean ,布尔值,System.Nullable`1)'。"}
当我打开一个视图,其中有一个带有SeriLog引用的viewmodel时,我在DesignTime中收到以下错误.
无法加载文件或程序集'Serilog,Version = 2.0.0.0,Culture = neutral,PublicKeyToken = 24c2f752a8e58a10'或其依赖项之一.Het systeem kan het opgegeven bestand niet vinden.myapp C:\ snip\Projects\snip\myapp\myapp\Views\MyViews\MyView.xaml
荷兰语字符串翻译成英语:"系统找不到文件"
该项目编译并运行良好,但我想要一个没有错误的设计时体验.现在这个错误破坏了我在VS2017中的设计时项目代码.我该怎么做才能解决这个错误?
已经尝试过:
我正在构建一个针对周年纪念版14393框架的UWP应用程序.
project.json serilog参考:
"Serilog": "2.4.0",
"Serilog.Sinks.RollingFile": "3.3.0",
Run Code Online (Sandbox Code Playgroud)
示例VS项目复制问题
我在DetailPage.xaml上使用mvvm-light viewmodel创建了一个空白的Template10项目,其中显示了serilog错误.
下载位置:
https://www.dropbox.com/s/uocjx0kuc1dknwt/Template10_Serilog_Sample.zip?dl=0
错误的屏幕截图
我正在ILogEventSink使用构建简单接收器示例创建我自己的SeriLog 接收器,目的是记录用户声明中的一些信息.要在Core中访问HttpContext,我通常会注入一个实例,IHttpContextAccessor但示例显示在扩展方法中创建接收器的实例,例如
public class MySink : ILogEventSink
{
private readonly IFormatProvider _formatProvider;
public MySink(IFormatProvider formatProvider)
{
_formatProvider = formatProvider;
}
public void Emit(LogEvent logEvent)
{
// How to get HttpContext here?
}
}
public static class MySinkExtensions
{
public static LoggerConfiguration MySink(
this LoggerSinkConfiguration loggerConfiguration,
IFormatProvider formatProvider = null)
{
return loggerConfiguration.Sink(new MySink(formatProvider));
}
}
Run Code Online (Sandbox Code Playgroud)
......然后使用水槽......
var log = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.MySink()
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
如何在接收器的Emit方法中访问当前的HttpContext?或者是否可以使用DI框架创建的接收器?!
我有一个运行Asp.Net Core 2框架的MVC站点,使用Serilog.AspNetCore v2.1.0对抗.Net 4.6.2运行时.
更新 - 解决方法 …
我在program.cs中有这个Serilog配置
public class Program
{
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.Build();
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.WriteTo.MSSqlServer(Configuration.GetConnectionString("DefaultConnection"), "dbo.Log")
.Enrich.WithThreadId()
.Enrich.WithProperty("Version", "1.0.0")
.CreateLogger();
try
{
BuildWebHost(args).Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog()
.Build();
}
Run Code Online (Sandbox Code Playgroud)
现在我想添加HttpContext.Current.User.Identity.Name …
我在服务器端使用控制台,文件和Graylog接收器为所有.NETCore服务使用Serilog。我还喜欢在Windows胖客户端(WPF应用程序)中使用它。
对于后者,我有一个问题,因为我看不到,如何在用户成功登录后添加另一个文件接收器。我需要将应用程序日志存储在全局AppData (Environment.SpecialFolder.CommonApplicationData)文件夹中,并将另一个用户日志存储在用户子文件夹中,例如:
var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
AppDataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), appName);
Directory.CreateDirectory(AppDataDir);
AppLogDir = Path.Combine(AppDataDir, $@"Logs");
Directory.CreateDirectory(AppLogDir);
Log.Logger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.Enrich.WithExceptionDetails()
.Enrich.FromLogContext()
.Enrich.WithProcessName()
.Enrich.WithThreadId()
.Enrich.WithAssemblyName()
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] " +
"ThreadId: [{ThreadId}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(Path.Combine(AppLogDir, $"{appName}-.log"), rollOnFileSizeLimit: true,
fileSizeLimitBytes: 1048576, retainedFileCountLimit: 30,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] " +
"[ThreadId: {ThreadId}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
然后,LoginViewModel在成功登录后以及配置了初始应用程序记录器很长时间之后,我就知道了用户名,并可以为该用户创建一个文件夹并将日志文件放在此处:
var userLogDir = Path.Combine(AppDataDir, userName); …Run Code Online (Sandbox Code Playgroud) 通过研究Serilog.Sinks.AzureTableStorage我有以下内容
在主要
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration) // the error happens here
.CreateLogger();
logger.Information("Hello, world!");
Run Code Online (Sandbox Code Playgroud)
在appsetttings.json中(使用不同的连接字符串)
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.AzureTableStorage" ],
"MinimumLevel": "Debug",
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": { "path": "%TEMP%\\Logs\\serilog-configuration-sample.txt" }
},
{
"Name": "AzureTableStorage",
"Args": {
"storageTableName": "mystoragetable",
"connectionString": "myconnectionstring"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Destructure": [
{
"Name": "With",
"Args": { "policy": "Sample.CustomPolicy, Sample" }
}, …Run Code Online (Sandbox Code Playgroud) 我已启用 SeriLog(最新版本)自记录功能,并且看到数百条消息说
达到最大解构深度
不知道这意味着什么以及这是否是我需要担心的问题。
有谁知道是什么触发了这条消息以及我是否做错了什么?
搜索了很长时间后,我找不到有关 Serilog 如何处理日志源清理的信息。又名反对“日志注入”或“日志伪造”的战斗(参见https://owasp.org/www-community/attacks/Log_Injection)。所有搜索都指向“依赖注入”,这是一个完全不同的主题:)
我假设通过使用带有字符串参数的 Serilog ( https://github.com/serilog/serilog/wiki/Writing-Log-Events ),可能的危险内容已被清除。但是,他们是吗?
有谁知道这是否已完成,我应该担心吗?
如果有人使用不带字符串参数的 Serilog,而是使用带有字符串连接的 Serilog(违反指令)怎么办?
serilog ×10
c# ×6
logging ×2
.net ×1
.net-core ×1
asp.net-core ×1
asp.net-mvc ×1
httpcontext ×1
mvvm-light ×1
security ×1
uwp ×1