Serilog doesn't log to file, only to console - mono

I'm currently working on a mono project and want to use Microsoft.Logging + Serilog there, but I stumble across the following problem:
When I configure Serilog by hand, it logs in both console and the file (if I have configured both parameters). But when I use a configuration file, Serilog always ignores logging to the file.
The configuration file is found and the parameters are read from there, because if I add "Console" there, Serilog logs into the console.
With these settings, Serilog should, as I understand it, log into the console as well as into the file. I'm expecting this log file in "folder with appsettings.json"/logs. But it only logs into the console. And when I delete "Console", it doesn't log anywhere. I don't understand why this is so I am posting a few sections of code that are fundamental. If I have not provided enough information, please write to me in comments under the question.
appsettings.json:
{
"Serilog": {
"Using": [
"Serilog.Sinks.Console"
],
"MinimumLevel": "Debug",
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithProcessId",
"WithThreadId"
],
"WriteTo": [
{
"Name": "File",
"Args": {
"Path": "logs/GUIDemo.log",
"FileSizeLimitBytes": "400000",
"RollingInterval": "Day",
"RetainedFileCountLimit": "15",
"OutputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj} {NewLine}{Exception}",
"shared": true
}
},
"Console"
]
}
}
Here is how I configure Serilog in one class, which methods are executed shortly after the application start:
private IContainer container;
private ILogger<Bootstrapper> logger;
...
public void OnStartup()
{
this.Configuration = this.ConfigureConfiguration();
var builder = new ContainerBuilder();
builder.RegisterModule<AutofacModule>();
this.container = builder.Build();
this.AddLogger();
this.logger = this.container.Resolve<ILogger<Bootstrapper>>();
this.LogApplicationStart();
}
And finally methods AddLogger(), LogApplicationStart() and LogApplicationStart():
private void AddLogger()
{
var loggerFactory = this.container.Resolve<ILoggerFactory>();
loggerFactory.AddSerilog();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(this.Configuration)
.CreateLogger();
}
private IConfigurationRoot ConfigureConfiguration()
{
return new ConfigurationBuilder().SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build();
}
private void LogApplicationStart()
{
this.logger.LogInformation("App is started");
}
After all of this, the output in the console is (yes, it is Godot):
Mono: Log file is:
'C:\Users\Albert\AppData\Roaming/Godot/mono/mono_logs/2021_01_27 12.46.37(105008).txt'
[12:46:38 INF] App is started
The Mono log file has nothing to do with my log file. I also tried to add Log.CloseAndFlush() at the the end of LogApplicationStart() which is currently the only method in the app, but it didn't help me as well.
Of course, I know there are many similar question here, but I could not find a solution for my problem.

Related

Prevent DefaultAntiforgery from logging errors

Is there a way to stop DefaultAntiforgery from logging errors? I see it takes an ILoggerFactory as parameter, which is a public type, but I don't know how to set it up since DefaultAntiforgery is internal.
I don't think this is a DI issue, but rather a configuration issue. What you want should be possible by configuring logging
Try something like this in your appsettings.json:
{
"Logging": {
// for all logging providers
"LogLevel": {
"Microsoft.AspNetCore.Antiforgery": "None"
},
// or just for the EventLog provider
"EventLog": {
"LogLevel": {
"Microsoft.AspNetCore.Antiforgery": "None"
}
}
}
}

Logging LogLevel-Information not showing in Windows event log [duplicate]

This question already has answers here:
How to write logs to EventLog by ILogger<T> in Asp.net Core?
(3 answers)
Closed 12 months ago.
I ran into some problems with logging **Information** Logs to Windows event log.
Starting from a blank ASP.NET Core-Web-API .Net 5
I edited the following to Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddEventLog(eventLogSettings =>
{
eventLogSettings.SourceName = "MyTestLog";
});
});
webBuilder.UseStartup<Startup>();
});
and wrote some sample logs into a Controler
public IEnumerable<WeatherForecast> Get()
{
_logger.LogCritical("Critical Log");
_logger.LogError("Error Log");
_logger.LogWarning("Warning Log");
_logger.LogInformation("Info Log");
_logger.LogDebug("Debug Log");
_logger.LogTrace("Trace Log");
...
}
If I Run it, it shows logs for Critical - Error - Warning - Information in Console. Matching what is configured in AppSettings.
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
In Windows event log it only shows Critical, Error and Warning -Logs, not caring for my appsettings whatsoever.
I'm sure this is an easy configuration problem, but i don't find any documentation for this.
How do I get Logs with Loglevel-Information in Windows event log ?
According to this article, you could find the ASP.NET Core provide the event logging feature. Unlike the other providers, the EventLog provider does not inherit the default non-provider settings.
If EventLog log settings aren't specified, they default to LogLevel.Warning.
To log events lower than LogLevel.Warning, explicitly set the log level. The following example sets the Event Log default log level to LogLevel.Information:
"Logging": {
"EventLog": {
"LogLevel": {
"Default": "Information"
}
}
}

Use serilog save log records

I want to save the printed information to txt text so that we can view important information.
Loggers are created using a LoggerConfiguration object:
Log.Logger = new LoggerConfiguration().CreateLogger();
Log.Information("No one listens to me!");
// Finally, once just before the application exits...
Log.CloseAndFlush();
This is some code I checked the document, I want to save the data in Json format, so that the structure is clear and easy for us to view, what do I need to do, thank you for your suggestions.
Configuring Serilog in ASP.NET Core:
Package:
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
appsettings.json:
{
"Serilog": {
"MinimumLevel": "Information",
"Override": {
"Microsoft.AspNetCore": "Warning"
},
"WriteTo": [
{
"Name": "Console "
},
{
"Name": "File",
"Args": {
"path": "Serilogs\\AppLogs.log",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
}
]
}
}
As shown above, the file receiver requires a parameter, in which we need to specify the log file name and file path. This path can be absolute or relative. Here, I specified a relative path, which will create a folder serilogs in the application folder and write to the file AppLogs.log in that folder.
Then add code in startup.cs to read these Serilog settings in the constructor, as shown below:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
Then change the code in program.cs to specify that Host Builder use Serilog in ASP.NET Core instead of the default logger:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Firstly you need to add a reference to Serilog.Sinks.File via nuget.
The next step is to add the destination for Logger:
.WriteTo.File(new JsonFormatter(), "log.json")
The full listing is:
Log.Logger = new LoggerConfiguration()
.WriteTo.File(new JsonFormatter(), "log.json")
.CreateLogger();
Log.Information("No one listens to me!");
// Finally, once just before the application exits...
Log.CloseAndFlush();
The output in log.json file is:
{"Timestamp":"2022-01-14T02:49:31.5111479+00:00","Level":"Information","MessageTemplate":"No one listens to me!"}
Is it what you need?

dotnet core logging showing info result always

I am learning .net core logging. I have read some blogs and docs also.
I am wondering why it's showing always "Microsoft.Hosting.Lifetime" Information logs every time with following settings.
{
"Logging": {
"LogLevel": {
"Default": "Error",
"Microsoft": "Error",
"Microsoft.Hosting.Lifetime": "Error",
"DemoWeb.Controllers.HomeController": "Error"
}
},
"AllowedHosts": "*"
}
To double check(If my appsettings.json is working) I added this in ConfigureService.
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(config =>
{
// clear out default configuration
config.ClearProviders();
config.AddConfiguration(Configuration.GetSection("Logging"));
config.AddDebug();
config.AddEventSourceLogger();
config.AddConsole();
});
services.AddControllersWithViews();
}
It's working as expected for my own added "HomeController" Class.
I just want to remove "Microsoft.Hosting.Lifetime" from console logs.
Thanks in advance
Firstly, as #KirkLarkin mentioned, in development, appsettings.Development.json configuration would overwrite values found in appsettings.json.
For more information, you can check : https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#appsettingsjson
want to remove "Microsoft.Hosting.Lifetime" from console logs
In your project, multiple logging providers can be enabled. If you just want to turn off Information level logs about "Microsoft.Hosting.Lifetime" from ConsoleLogger, you can try to apply log filter rule(s) as below.
services.AddLogging(config =>
{
// clear out default configuration
config.ClearProviders();
config.AddConfiguration(Configuration.GetSection("Logging"));
//add log filter for ConsoleLoggerProvider
config.AddFilter<ConsoleLoggerProvider>("Microsoft.Hosting.Lifetime", LogLevel.Error);
config.AddDebug();
config.AddEventSourceLogger();
config.AddConsole();
});
And you can achieve same by configuring logging for that specific provider.
"Console": {
"IncludeScopes": true,
"LogLevel": {
"Microsoft.Hosting.Lifetime": "Error"
}
}

Load asset file at Startup failed, file does not exists

I need to load some asset data to my middleware, but it seems like it can't load the file.
Here's the folder structure:
As you can see, it's already set to "Copy if newer". And the file does get copied over to the bin folder:
Here's the code at ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
var assetFile = Configuration["Assets/Files"];
var testExist = File.Exists(assetFile); // This will be false
//services.AddAsset();
}
Here's the appsettings.json:
{
"Assets": {
"Files": "Assets/something.zip"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
As of now, my only guess is there is file size limit? The .zip file is 165MB large. Just my wild guess, else I don't know why it couldn't find my file.
My guess is that the config setting ins't read properly, that's why it cannot locate the file.
Try replacing this line:
var assetFile = Configuration["Assets/Files"];
with this one:
var assetFile = Configuration["Assets:Files"];
Notice that I used colons to navigate in the appsettings.json keys, instead of a forward slash.