You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Web API Windows服务中Serilog首次请求后停止日志

问题:Windows服务运行的ASP.NET Core Web API Serilog日志异常

这是一个以Windows服务运行的ASP.NET Core Web API,遇到如下Serilog日志异常:

  • 服务启动后及接收少量Web请求前,日志能写入指定的绝对路径文件,但之后日志停止输出
  • 日志同时会写入到system/windows32目录下的文件中
  • 从未在Serilog自日志文件中看到任何输出

已尝试的操作

  • 添加Serilog自日志功能
  • 按照文档示例调用builder.Services.AddSerilog
  • 不在UseSerilog调用中传入Log.Logger(按文档说明本该自动使用该实例)
  • 搜索类似问题,发现有报告称Serilog日志写入windows/system32是因为未使用绝对路径或未设置工作目录,但我使用的是绝对路径,该情况不适用
  • 其他诸多已记不清的尝试

Program.cs 代码

using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.FileProviders;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using Serilog.Extensions.Logging;
using Log = Serilog.Log;

public static class Program
{
    public static void Main(string[] args)
    {
        try
        {
            // set current directory to working directory

            var builder = WebApplication.CreateBuilder();
            
            builder.Logging.ClearProviders();
            ServiceUtils.SetupLog();
            builder.Host.UseSerilog(Log.Logger);

            var process_name = Assembly.GetEntryAssembly()?.GetName().Name ?? "";
            Log.Information(
                $"\n\n***** Starting {process_name} on {Environment.MachineName} with command {Environment.CommandLine}\n"
            );

            builder.Host.UseWindowsService();
            // ...

            app.UseSerilogRequestLogging();
            // ...
        }
        catch()
        {
            // ..
        }
    }
}

SetupLog方法代码

using System.Diagnostics;
using System.Reflection;
using System.Runtime.Versioning;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using Serilog.Events;

public static void SetupLog()
{
    var entry = Assembly.GetEntryAssembly().GetName();
    //var base_dir = AppContext.BaseDirectory;
    var base_dir = "C:\\some-dir";

    var log_dir = Path.Combine(base_dir, $"{entry.Name}_log");
    var log_name = $"{Process.GetCurrentProcess().ProcessName}_{Environment.MachineName}.log";
    var log_path = Path.Combine(log_dir, log_name);

    Serilog.Debugging.SelfLog.Enable(msg =>
            {
                File.AppendAllText(@$"{base_dir}\\serilog-selflog.txt", msg + Environment.NewLine);
            });

    Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .MinimumLevel.Override("Microsoft.AspNetCore.Hosting", LogEventLevel.Warning)
                .MinimumLevel.Override("Microsoft.AspNetCore.Mvc", LogEventLevel.Warning)
                .MinimumLevel.Override("Microsoft.AspNetCore.Routing", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .Enrich.WithProcessId()
                .Enrich.WithMachineName()
                .Filter.ByExcluding(
                    (e) =>
                    {
                        var path = e.Properties.ContainsKey("RequestPath")
                            ? e.Properties["RequestPath"].ToString().Replace("\"", "")
                            : "";
                        return HealthCheckIgnorePaths.Contains(path);
                    }
                )
                .WriteTo.Debug(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug)
                .WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)
                .WriteTo.File(log_path, rollingInterval: RollingInterval.Day)
                .WriteTo.NewRelicLogs(
                    endpointUrl: "https://log-api.newrelic.com/log/v1",
                    applicationName: $"{entry.Name}",
                    licenseKey: someKey
                )
                .CreateLogger();

    Log.Debug($"Beginning application log.\nLog file path: [{log_path}]\n");
}

内容的提问来源于stack exchange,提问作者Pete

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 05:40:07