如何在 docker 容器内运行的 .net core 应用程序中写入日志,以便日志消息显示在docker logs <container-id>
或者在 Kitematic UI 中?
我几乎尝试了所有方法,但最终总是没有来自 dotnet 应用程序的日志。我在 NODE.js、nginx、rabbitmq 等容器中拥有的所有其他非 dotnet 应用程序都可以毫无问题地写入日志。
这是我已经尝试过的:
- 控制台应用程序(.NET Core)使用
Console.WriteLine
- 使用 ILogger 接口的 ASP.NET Core 应用程序(使用带有 docker 支持的 VS 模板后的默认设置)
- 在控制台/ASP.NET Core 应用程序中使用 log4net(日志记录实际上适用于例如 RollingFileAppender)和 ConsoleAppender
我找不到遇到同样问题的人(stackoverflow、google、github 问题),所以我认为我在这里遗漏了一些重要的东西。
更新1:
这是我当前的设置:
- Windows 10 专业版
- 适用于 Windows 17.12.0-ce 的 Docker
- docker-compose 版本 1.18.0,内部版本 8dd22a96
- 运行 Linux 容器
更新2:
工作 Dockerfile 的示例(NodeJS 应用程序)
FROM node:9-slim
WORKDIR /app
EXPOSE 80
ENV NODE_PATH=/node_modules
ENV PATH=$PATH:/node_modules/.bin
COPY ./MyApp ./
RUN npm install
RUN npm run build
CMD [ "npm", "start" ]
不工作的 Dockerfile 示例(ASP.NET Core,由 Visual Studio 生成)
FROM microsoft/aspnetcore:2.0 AS base
WORKDIR /app
EXPOSE 80
FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src
COPY *.sln ./
COPY DockerLoggingTest2/DockerLoggingTest2.csproj DockerLoggingTest2/
RUN dotnet restore
COPY . .
WORKDIR /src/DockerLoggingTest2
RUN dotnet build -c Release -o /app
FROM build AS publish
RUN dotnet publish -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "DockerLoggingTest2.dll"]
正如您所看到的,它没有什么特别的。所以问题一定出在 .NET Core 中,因为所有其他类型的应用程序日志都正常。
将以下内容添加到 appsettings.json
"Logging": {
"LogLevel": {
"Default": "Information",
"System": "Information",
"Microsoft": "Information"
},
"Console": {
"IncludeScopes": true
}
}
确保您的项目配置为复制您的应用程序设置,在 YourProject.csproj 内确保
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
然后我将配置添加到日志记录服务中。
services.AddLogging(builder =>
builder
.AddDebug()
.AddConsole()
.AddConfiguration(configuration.GetSection("Logging"))
.SetMinimumLevel(LogLevel.Information)
);
希望这可以帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)