在Kubernetes容器中,如何记录.NET Core 2.0应用程序的日志?

28

我在.net core 2.0中编写了一些Web API,并使用Kubernetes集群内的Docker容器部署它。 我正在使用以下日志配置,但无法在Kubernetes pod控制台中看到任何日志。 我是不是漏掉了什么?

appsettings.json和appsettings.Development.json中的日志部分。

{
  "Logging": {
    "IncludeScopes": true,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    },
    "Console": {
      "LogLevel": {
        "Default": "Information",
        "System": "Information",
        "Microsoft": "Information"
      }
    }
  }
}

Program.cs文件内部:

public static IWebHost BuildWebHost(string[] args)
{
    return new WebHostBuilder()
        .UseKestrel()
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;

            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

            if (env.IsDevelopment())
            {
                var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                if (appAssembly != null)
                {
                    config.AddUserSecrets(appAssembly, optional: true);
                }
            }

            config.AddEnvironmentVariables();

            if (args != null)
            {
                config.AddCommandLine(args);
            }
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
        })
        .UseDefaultServiceProvider((context, options) =>
        {
            options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
        })
        .UseStartup<Startup>()
        .Build();
}

其他类中登录示例:

_logger.LogInformation("This log should go in kubernetes pod console");

2
你在使用Visual Studio的调试模式运行代码时遇到了问题吗? - divyang4481
我也遇到了同样的问题。看起来ILogger没有输出到Kubernetes的标准输出,因此无法在k8s日志机制中显示。对我来说,这是在Linux Ubuntu容器上发生的。 - irperez
当您在本地运行容器时,是否可以获取日志信息?例如:docker run <image>docker logs <container> - Serge
我无法使用与上面发布的相同的 .netcore 2.1/minikube 代码重现此问题。是否有可重现的示例代码可供调查? - Peter Bons
2个回答

3

您是否尝试过使用常见的第三方包来进行强大日志记录?这可能符合您的需求!下面的代码展示了如何在 Program.cs 中注入 Serilog,并可用于通过多个通道输出其日志(我个人正在使用 macOS 上的本地 minikube 和 GCP 上的分段环境)。

WebHost.CreateDefaultBuilder(args)
                .UseSerilog((context, configuration) =>
                {
                    configuration
                        .MinimumLevel.Debug()
                        .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                        .MinimumLevel.Override("System", LogEventLevel.Warning)
                        .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
                        .Enrich.FromLogContext()
                        .WriteTo.Console(
                            outputTemplate:
                            "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}",
                            theme: AnsiConsoleTheme.Literate);
                })

从上面的示例中希望得到的输出在Kubernetes中应该类似于:
 xxxxx@iMac  ~/Projects/xxxxx   xxxxbranch/xxx-xxx  kubectl logs xxxx-xxxx-6b9dd8dc67-vc9ch
[2020-08-04 12:11:37 Warning] Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository
Storing keys in a directory '/xxxxxxxxx/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.

[2020-08-04 12:11:37 Warning] Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager
No XML encryptor configured. Key {xxxxxx} may be persisted to storage in unencrypted form.

[2020-08-04 12:11:37 Warning] Microsoft.AspNetCore.Server.Kestrel
Overriding address(es) 'https://+:8081'. Binding to endpoints defined in UseKestrel() instead.

Hosting environment: Production
Content root path: /app
Now listening on: https://0.0.0.0:8081
Application started. Press Ctrl+C to shut down.

这些输出结果也被存储在谷歌云日志仪表板中。


0
你尝试在你的appsettings中的Console键下添加"IncludeScopes": true了吗?
"Console": {
  "IncludeScopes": true
    "LogLevel": {
      "Default": "Information",
      "System": "Information",
      "Microsoft": "Information"
    }
}

我能够通过运行以下kubectl命令来流式传输日志:

kubectl logs --follow -c [容器名称] [Pod名称]

运行Pod后的响应:

←[40m←[32minfo←[39m←[22m←[49m: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://[::]:80
←[40m←[32minfo←[39m←[22m←[49m: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
←[40m←[32minfo←[39m←[22m←[49m: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
←[40m←[32minfo←[39m←[22m←[49m: Microsoft.Hosting.Lifetime[0]
      Content root path: /app

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