Use serilog save log records - asp.net-core

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?

Related

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"
}
}
}

How does Serilog retrieve key information?

I need a requirement like this, I need to create a log message record of any kind using the logging framework. Then record some logs in some key places, and then I need to retrieve some information from it, how is this done?
enter image description here
Like this, or is there any other framework that is easier to implement? Any help is greatly appreciated.
Required Nuget Packages:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<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>
<ItemGroup>
<Folder Include="MyLogInfo\" />
</ItemGroup>
</Project>
appsettings.json configuration:
{
"Serilog": {
"MinimumLevel": "Information",
"Override": {
"Microsoft.AspNetCore": "Warning"
},
"WriteTo": [
{
"Name": "Console "
},
{
"Name": "File",
"Args": {
"path": "MyLogInfo\\MyLogInfo.txt",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
}
]
}
}
Then add code in startup.cs to read these Serilog settings in the constructor:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
Finally change the code in program.cs to specify that Host Builder uses Serilog from ASP.NET Core instead of the default logger:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Result:
For more details, please refer to this article:
Implementing logging with Serilog
More logging frameworks can read this:
Logging in .NET Core and ASP.NET Core
Then you want to read information from this log?
You can read this article:
https://learn.microsoft.com/en-us/previous-versions/windows/apps/hh758325(v=win.10)

Custom directories names in Vue + ASP.NET Core Web API

Help me please to configure my vue app. I want to use Vue over ASP.NET Core Web API.
This is what I have done:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSpaStaticFiles(options => options.RootPath = "Client/Dist");
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "api",
pattern: "api/{controller}/{action}/{id?}");
});
app.UseSpaStaticFiles();
app.UseSpa(x => { x.Options.SourcePath="Client/Dist"; });
}
Then I created vue app with vue-cli. I chose configs built in package json. And then I renamed directories:
And I put these lines into package.json
"vue": {
"pages": {
"index": {
"entry": "Sources/Index.ts",
"template": "Public/Index.html",
"filename": "index.html"
}
},
"outputDir": "Dist"
}
The build process was successful, but
Favicon.ico was not copied to the Dist folder after build
In the browser there is only white screen. There are no any errors in the console, all requests are successful. Vue just doesn't add anything to the root node (<div id ="app">)
I think, that the problem is in my custom filenames and I don't know what I should add into config to fix that

Serilog doesn't log to file, only to console

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.

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.