How can I log messages from an ASP.NET Core application to a specific file on Linux?
Logs go where you tell them to go, not a specific location. /var/log/message
is the location used by the Debug Provider only.
You need to specify which logging providers you want to use in the logging configuration of your project, as shown in the Logging in .NET Core article.
There's no built-in file provider and there's an ongoing discussion about whether there should be one. Logging to files isn't as simple as it sounds at first - how should the messages be formatted? What about rolling files? File names? Perhaps you want errors and verbose messages to be written to different files? Or use different files per subsystem/area/logger/business in your application, eg one log for the sales service, another to log external service calls?
There are a lot of good open source logging libraries, like Serilog and NLog that address these concerns. Some of the most popular ones are listed in .NET Core's documentation. .NET Core's logging can be configured to easily use those libraries.
For example, you can add a Serilog file target with the appropriate package.
To use it, you need to add a reference to the package, eg in your csproj
file :
<PackageReference Include="Serilog.Extensions.Logging.File" Version="2.0.0" />
And add it to the logging configuration with a call to AddFile
:
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddFile("path/to/Logs/myapp-{Date}.txt");
})
.UseStartup<Startup>()
.Build();
The {Date}
argument is used to create rolling log files per date.
You can combine multiple loggers,eg you can write to the console with logging.AddConsole()
or keep writing to /var/log/message
during development with logging.AddDebug();
You can find many logging providers is you search for Extensions.Logging in NuGet.
You could also integrate other libraries like Serilog in your application and use their loggers. For example, you can use the Serilog.Sinks.Fluentd package to target Fluentd
No logs are showing up in Linux CentOS 8 using .NET core 3 / 3.1
How about adding .WriteTo.Console()
to that serilog setup? You'll also need to have this package in the relevant csproj file: https://www.nuget.org/packages/serilog.sinks.console/
NLog - create log file at specific directory in linux
Make sure to use Unix-path, so stop using backslash \
Ex. instead of ${logDir}\log-${shortdate}.log
then it should be ${logDir}/log-${shortdate}.log
.
If still having issues then try to activate the NLog InternalLogger and check the output https://github.com/NLog/NLog/wiki/Internal-Logging
How to customise log file in serilog
The GUID is a request id:
https://github.com/serilog/serilog-extensions-logging-file/#file-format
To customize it, specify an output template:
loggerFactory.AddFile("Logs/EigenLog-{Date}.txt", outputTemplate:
"{Timestamp:o} [{Level:u3}] {Message} {Properties:j} ({EventId:x8}){NewLine}{Exception}"
);
Removing Responding from memory cache messages form info log level
This seems to be logged from the WebOptimizer namespace (I checked the source on github) which should make it easy to filter out using appsettings. Just add a "WebOptimizer" key and set it to only show "Warning" and higher.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"WebOptimizer": "Warning"
}
}
}
How to configure Azure App Service logging provider for an ASP.NET Core app?
I couldn't make it work using AzureWebAppDiagnostics logging provider, but I've managed to solve my problem by using Serilog provider with a file sink.
In program.cs:
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.File(@"../../LogFiles/azure-diagnostics-", fileSizeLimitBytes: 50 * 1024, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 5)
.CreateLogger();
try
{
CreateHostBuilder(args).Build().Run();
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls("http://*:8080");
webBuilder.UseStartup<Startup>();
});
}
UseSeriLog() call replaces the default MS log factory so I could also delete the logging configuration from appsettings.
Now I can see my custom log files appearing in the /home/LogFiles directory as expected.
Related Topics
How to Log from a Non-Root Debian Linux Daemon
Initramfs Built into Custom Linux Kernel Is Not Running
Jenkins Running at Very High CPU Usage
How to Install Xclip on an Ec2 Instance
Put Command Output into String
Install Sqlite3 Dev and Other Packages in Centos
How to Create Ansible Playbook to Obtain Os Versions of The Remote Hosts
In Shell, Split a Portion of a String with Dot as Delimiter
How to Check If The Sed Command Replaced Some String
How to Avoid Having Version Numbers in .So File Name
What Does '#Pragma Gcc Optimize ("O3")' Mean
Installing Ffmpeg on Amazon Linux - Cpp, Gcc & Libstdc++ Dependancies
Need Explanation on Pri Standard Format Specifier for Ps - Possible Bug in Documentation
Cdc_Acm: Failed to Set Dtr/Rts - Can Not Communicate with Usb Cdc Device