Serilog在ASP.NET Core 2.2中使用InProcess托管模型时无法将日志写入文件

8

如果我在ASP.NET Core 2.2中使用新引入的InProcess托管模型,如下所示:

<PropertyGroup>
  <TargetFramework>netcoreapp2.2</TargetFramework>
  <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>

Serilog不会将日志写入文件。但是,如果我从.csproj中删除<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>,则一切都按预期工作。

我的Program类中的Serilog配置如下:

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information() // Set the minimun log level
            .WriteTo.File("Logs\\log-.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7) // this is for logging into file system
            .CreateLogger();

        try
        {
            Log.Information("Starting web host");
            CreateWebHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }

    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logging => { logging.ClearProviders(); }) // clearing all other logging providers
            .UseSerilog(); // Using serilog 
}

请问专家有什么想法?

1
请注意,托管进程与自托管进程具有不同的默认目录。因此,在启动期间您可能需要设置它,或者使用绝对路径(通过appsettings.json、环境变量等)。 - Tseng
2个回答

14

正如在您的问题评论中建议的那样,当使用InProcess托管模型时,应用程序的当前目录与OutOfProcess托管模型不同。对于 InProcess ,该目录是 IIS 本身的位置 - 例如 C:\Program Files\IIS Express,这意味着您的日志文件被写入到 C:\Program Files\IIS Express\Logs\log-.txt(假设相关权限已设置)。

解决方法详见该 GitHub 问题,其中提供了一个辅助类(CurrentDirectoryHelpers),可设置正确的当前目录。 SetCurrentDirectory 静态方法使用 PInvoke,确定应用程序是否从 IIS 中运行,如果是,则根据完整的应用程序路径设置当前目录。使用此方法如下:

public class Program
{
    public static void Main(string[] args)
    {
        CurrentDirectoryHelpers.SetCurrentDirectory();

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information() // Set the minimun log level
            .WriteTo.File("Logs\\log-.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7) // this is for logging into file system
            .CreateLogger();

        ...
    }
}

为了完整起见,这里是CurrentDirectoryHelpers

using System;

namespace SampleApp
{
    internal class CurrentDirectoryHelpers
    {
        internal const string AspNetCoreModuleDll = "aspnetcorev2_inprocess.dll";

        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        [System.Runtime.InteropServices.DllImport(AspNetCoreModuleDll)]
        private static extern int http_get_application_properties(ref IISConfigurationData iiConfigData);

        [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
        private struct IISConfigurationData
        {
            public IntPtr pNativeApplication;
            [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]
            public string pwzFullApplicationPath;
            [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]
            public string pwzVirtualApplicationPath;
            public bool fWindowsAuthEnabled;
            public bool fBasicAuthEnabled;
            public bool fAnonymousAuthEnable;
        }

        public static void SetCurrentDirectory()
        {
            try
            {
                // Check if physical path was provided by ANCM
                var sitePhysicalPath = Environment.GetEnvironmentVariable("ASPNETCORE_IIS_PHYSICAL_PATH");
                if (string.IsNullOrEmpty(sitePhysicalPath))
                {
                    // Skip if not running ANCM InProcess
                    if (GetModuleHandle(AspNetCoreModuleDll) == IntPtr.Zero)
                    {
                        return;
                    }

                    IISConfigurationData configurationData = default(IISConfigurationData);
                    if (http_get_application_properties(ref configurationData) != 0)
                    {
                        return;
                    }

                    sitePhysicalPath = configurationData.pwzFullApplicationPath;
                }

                Environment.CurrentDirectory = sitePhysicalPath;
            }
            catch
            {
                // ignore
            }
        }
    }
}

2

尝试升级 .Net Core 版本。这个问题在 2.2.3 中似乎已经被修复。

原始答案:最初的回答


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接