I'm trying to implement Serilog in a .Net Core library to have a good abstraction for this Third party and be able to use it on different project that are in my Solution.
So I configure Serilog like the example in their GitHub
if(Log.Logger == null){
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.LiterateConsole()
.WriteTo.RollingFile("logs/myUsefullLogs.txt")
.CreateLogger();
}
And I log an information like this :
Log.Information(message,ex,source);
Log.CloseAndFlush();
If I put a breakpoint all seems to work perfectly but when I search the file I'm not able to find it.
Somebody already face to this in macOS?
Log.Logger will never have the value null, so your configuration code above will never run.
When logging is not configured, Log.Logger is assigned an instance of the (internal) SilentLogger class: https://github.com/serilog/serilog/blob/dev/src/Serilog/Log.cs#L43.
Related
When starting up my .Net 6 Web Api project, in the program.cs I am using Two-stage initialisation from serilog-aspnetcore to initially output to console, and then in the second phase, output logs to a database.
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateBootstrapLogger();
// down from the above, the proper logging configuration
// add logging
builder.Host.UseSerilog(
(context, services, configuration) =>
configuration.ReadFrom
.Configuration(context.Configuration, "Serilog")
.ReadFrom.Services(services)
.Enrich.FromLogContext()
);
Inside my configuration I am calling
"autoCreateSqlTable": true,
The problem is, it is not until after I have run var app = builder.Build(); that I have initialised my database (migrating via EF).
// execute database initialiser to ensure database is current
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var initialiser = services.GetRequiredService<DbInitialiser>();
initialiser.Run();
}
This is causing errors as serilog is attempting to create the logging table before I have created the database.
Is there a way to delay transitioning to using the proper serilog configuration until after I have initialised the database successfully?
I could create the logging table via EF, but I would still be using the second stage config before the setup completes (i.e. I only want console logging until database logging occurs).
I have attempted running the two phase initialisation as per instructions and it is attempting to create the log table before ef initialisation.
I have attempted to manually create the logger after initialisation via:
Log.Logger = new LoggerConfiguration()
.ReadFrom
.Configuration(builder.Configuration, "Serilog")
.ReadFrom.Services(app.Services)
.Enrich.FromLogContext()
.CreateLogger();
But then no logs are created in the database.
I currently have several .Net windows services running on my server. Is there a way to attach a console app to the service to get all of the ILogger data? I have had issues where the service runs perfectly as a console app/worker service but as soon as I run it as a windows service, it just sits there and does nothing.
I did find an article about attaching the VS debugger to the process, but this will not work with our network security.
I am open to any other suggestions as well.
The technical answer is no, but as #Fildor mentioned, you would set up a log sink of some sort. The file logger is just an example, but you can also have the logs send emails, post to some cloud logging service such as splunk or cloudwatch, etc.
One issue you may run into is that you need to capture an error prior to ILogger being available and properly configured for you. Here is a guide I followed for capturing startup errors using NLog: https://alistairevans.co.uk/2019/10/04/asp-net-core-3-0-logging-in-the-startup-class-with-nlog/
Startup classes are no longer necessary in the latest .NET version, so I modified their example to be code you would have in Program.cs:
// NLog: setup the nlog config first
NLogBuilder.ConfigureNLog("nlog.config");
try
{
var host = Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
// Use NLog to provide ILogger instances.
.UseNLog()
.Build();
host.Run();
}
catch (Exception ex)
{
var logger = nlogLoggerProvider.CreateLogger(typeof(Program).FullName);
}
}
Here's the list of available log sinks you can configure in that nlog configuration file: https://nlog-project.org/config/
This same thing can be accomplished with other log providers you may already be using such as Serilog, Log4Net, etc.
I want to create serilog logger file using docker image. I am able to create a file in console app but not able to create using docker.
Here is my sample code,
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File(fileName, rollingInterval: RollingInterval.Day)
.WriteTo.File(#"C:\log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
In short, the docker idea is to isolate the application from the host it is running on. Your app is trying to access the 'c:\log.txt' file which resides on host, not the container. You can write to the file inside the container by specifying the path like '/app/log.txt' (note the linux-style).
If you really need the host-side log file, the more complicated approaches are required - this SO answer may help:
Expose log file outside docker container
I am writing an uwp app with C# and I would like to use serilog to write logfiles.
When I do it in a .NET Core Console application it creates the file with the wanted content.
In the uwp I can show the log messages on the GUI, but no log file is created (yes, I have broadFileSystemAccess).
My code:
Log.Logger = new LoggerConfiguration().WriteTo.File("log.txt").CreateLogger();
Log.Debug("TEST");
Log.CloseAndFlush();
I would expect that it creates log.txt file in the directory which can be get with Windows.Storage.ApplicationData.Current.LocalFolder like
storageFolder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
does.
Can anyone tell me what I have to change or to consider to log to a file with serilog in my uwp app?
One of the great things about Serilog is that it's open-source and you can look at its source code and see what it is doing / how it works.
If you peek at the source code of the File sink, you'll notice that it is simply opening a file via System.IO.File.Open on the same folder where your app is running, which running from Visual Studio is probably going to be something like C:\Users\augustoproiete\MyApp\MyUwpApp\bin\x64\Debug\AppX\ where you don't have access to write file.
That means you have to be explicit about where to store the file, for example in the application data folder of your app. E.g.:
var logFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "log.txt");
Log.Logger = new LoggerConfiguration().WriteTo.File(logFilePath).CreateLogger();
Log.Debug("TEST");
Log.CloseAndFlush();
I'd recommend you read the Debugging and Diagnostics page on Serilog's docs, as it explains how you see error messages from Serilog - which you'd have seen that it was failing to create a file and the path it was using.
Thank yu for your answer!
I thought that the local folder path is automatically used, so I did not try that.
I jus had to modify the code as follows
var logFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "log.txt");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose() //otherwise Debug is not logged
.WriteTo.File(logFilePath)
.CreateLogger();
Log.Debug("TEST");
Log.CloseAndFlush();
then it woked and wrote the Debug message to the log file :)
Thank you very much!
I want to log Information - Fatal with Serilog in my ASP.NET Core Web Application, using .NET Core 3.0
I want to log this data in different files (which was already asked and answered but my case is a little different I think):
information.log => information about what the application did (only
using the automatic logging of Serilog / Microsoft)
error.log => All errors / unhandled exceptions that happen
other_information.log => (don't really have a name for this one) information about the program BUT only log messages created by me
I just can't figure out how to distinguish between information logs from Microsoft and my own.
I have found a question / answer on how to disable logging from Serilog / Microsoft but doing so it deactivates it for all LogWriters, How to turn off the logging done by the ASP.NET core framework
.
Then I found an answer to another question which maybe is exactly what I'm looking for, but I don't understand what happens so I prefer to not use it, because I don't like magic because if there is a problem, fixing it is a lot more time-consuming, Can I log to separate files using Serilog?.
I also found another question that looks similar: Serilog : Log to different files
but I don't understand this one either.
So if one of those really is the solution to my Problem I would be grateful if someone could explain it to me.
This is the Logger Configuration that I have until now, all it does is log all Information in one file and all errors in the other one.
using Serilog;
using Serilog.Events;
...
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console()
.WriteTo.Logger(l => l
.Filter.ByIncludingOnly(e => e
.Level == LogEventLevel.Information)
.WriteTo.File(#"Logs\Info.log"))
.WriteTo.Logger(l => l
.Filter.ByIncludingOnly(e => e
.Level == LogEventLevel.Error)
.WriteTo.File(#"Logs\Error.log"))
.CreateLogger();
And as I said, this works just fine to log all the information in one file and all the Errors in the other, but I don't know how to continue.
EDIT: I found the configurations I have at the moment from an answer to this question: Serilog - multiple log files
I believe you just need to filter your log based on the property SourceContext, which is explained here: Filter Serilog logs to different sinks depending on context source?