Serilog does not log to file after exception has occured - c#

I am using serilog in my .Net core 3.1 CONSOLE project. It works perfectly fine usually but if there is any exception, it logs the exception and then it stops logging all together for all subsequent runs of that app. I need to delete the log file and it starts working again.
Not sure what I am doing wrong or missing anything. Please help.
Here is the serilog configuration.
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\Logs\\MyLogs.log",
"rollingInterval": "Day",
"fileSizeLimitBytes": 5000,
"rollOnFileSizeLimit": true
}
}
] }
And here is how I am using it in generic host
return Host.CreateDefaultBuilder()
.ConfigureServices(( hostContext,services ) =>
{
...
})
.ConfigureAppConfiguration(config =>
{
config.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("AppConfigs.json");
})
.UseSerilog(( context,builder ) =>
{
builder
.ReadFrom.Configuration(context.Configuration);
});

This was a stupid mistake on my part. The issue was
"fileSizeLimitBytes": 5000,
which is 5 kb. The exception text was much bigger which was causing it to be more than the limit. And
"rollOnFileSizeLimit": true
was not working because I forgot to add Serilog.Sink.File package. Once I added that and changed the limit, it was all fine. Thanks for the replies.

Related

Sending logs to DataDog using a Serilog sink not working

Context:
Having looked over numerous answers and documentation. I am having to resort to asking others and I am thankful for your help.
C# configuration: https://docs.datadoghq.com/logs/log_collection/csharp/?tab=serilog
Support EU endpoints (My DataDog is on an eu server): https://docs.datadoghq.com/logs/log_collection/?tab=host#supported-endpoints
Github documentation for Serilog: https://github.com/DataDog/serilog-sinks-datadog-logs
My set up:
I have a DataDog trial account
I have a DataDog agent installed locally but I actually want to send logs to DataDog with an agentless approach
My logger makes logs into my Log/log.json files although It doesn't seem to update the file immediatley and can take several minutes to finally place the information into the file (no idea why)
I have the following dependencies installed as per the serilog documentation:
I have a .Net 6 project for an Angular App.
I have an appsettings.json that looks like this:
{
"AllowedHosts": "*",
"ConnectionStrings": {
"SitePageToSitePageModernConnection": "Data Source=.\\SQLEXPRESS;Initial Catalog=Blah;Integrated Security=True;MultipleActiveResultSets=True;TrustServerCertificate=True"
},
"Serilog": {
"Using": [
"Serilog.Sinks.File",
"Serilog.Sinks.Console",
"Serilog.Sinks.Datadog.Logs"
],
"MinimumLevel": {
"Default": "Error",
"Override": {
"Microsoft": "Error",
"System": "Error",
"My.App.Namespace.Something": "Information"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log.json",
"rollingInterval": "Day", // When a new file is created
"flushToDiskInterval": "00:00:01", // Currently does nothing. seems to be overwritten by operating system's paging cache interval (whatever that is)
"retainedFileCountLimit": 7 // How many files should be retained over the days specified by rollingInterval
}
},
{
"Name": "DatadogLogs",
"Args": {
"apiKey": "d7...b07",
"source": "something",
"host": "noideawhatgoeshere",
"configuration": {
"Url": "http-intake.logs.datadoghq.eu"
}
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId"
],
"Properties": {
"Application": "MyApplicationSample"
}
}
}
I am setting up the Serilog in the following manner:
// WebApplicationBuilder builder...
builder.Services.AddLogging(loggingBuilder =>
{
ConfigurationManager configurationManager = builder.Configuration;
Logger logger = new LoggerConfiguration()
.ReadFrom
.Configuration(configurationManager)
.CreateLogger();
// Adds serilog to the logging providers
loggingBuilder.AddSerilog(logger);
});
In a controller, I am using ILogger<MySiteController> to log.
// constructor injects:
...ILogger<MySiteController> _logger...
// call to controller runs some logs:
logger.LogInformation("Test information");
logger.LogError("Test error");
logger.LogWarning("Test warning");
My question/problem:
None of my logs end up in DataDog. Any ideas what I'm missing or misunderstanding?
The URL configured, in this case, was incorrect and should have been:
"configuration": {
"url": "https://http-intake.logs.datadoghq.eu",
"port": 443
}
For more information, I have laid out some comments to help others in the future:
{
// ...
//"AllowedHosts": "*",
// ...
// Serilog framework can look at this to configure itself
"Serilog": {
// This determines which of the types of logging you want to have
"Using": [
// This is for logging into a file in a static manner
"Serilog.Sinks.File",
// This is for logging into a file that can be configured to log for a day and then create a new file at the next day (a rolling file, get it?)
"Serilog.Sinks.RollingFile",
// This will allow logs to go into your console. Console in this case (for an Angular driven app, means the Terminal that appears when you launch your app)
"Serilog.Sinks.Console",
// This will allow logging to Datadog
"Serilog.Sinks.Datadog.Logs"
],
// These are the log levels you want to support
"MinimumLevel": {
// By default, you could say "I only want to see errors coming up"
"Default": "Error",
// If you are wanting to see information or debug or trace etc logs from other specific c# class namespaces, then you can configure them here
"Override": {
// Anything in a namespace that starts with `Microsoft` we only care about Errors being flagged (for example)
"Microsoft": "Error",
// Anything in a namespace that starts with `System` we only care about Errors being flagged (for example)
"System": "Error",
// If you had a tool with a C# class's namespace of "My.Tooling.Test", you, in this case will probably want to see all the logs you raise. so we could set this to Information (for example)
"My.Tooling.Test": "Information"
}
},
// Given that we have defined which frameworks we want to make use of in the "Using" section, we can now use the framework functionality for Console, File, RollingFile, Datadog, etc.
"WriteTo": [
// Tells Serilog to log stuff to the console
{
"Name": "Console"
//... You can configure more here but you'll need to Google that yourself
},
// Tells Serilog to log stuff to a File
{
"Name": "File",
//... You can configure more here but you'll need to Google that yourself
"Args": {
"path": "App_Data\\logs\\log.txt",
"rollingInterval": 3,
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss,fff} [P{ProcessId}/D%APP_DOMAIN_ID%/T{ThreadId}] {Level:u4} {CorrelationId} {UserId} - {Message:lj}{Exception}{NewLine}"
}
},
// Tells Serilog to log stuff to a Rolling File
{
"Name": "RollingFile",
//... You can configure more here but you'll need to Google that yourself.
"Args": {
"path": "App_Data\\logs\\DiagnosticTraceLog.txt{RollingDate}",
"shared": true,
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss,fff} [P{ProcessId}/D%APP_DOMAIN_ID%/T{ThreadId}] {Level:u4} {CorrelationId} {UserId} - {Message:lj}{Exception}{NewLine}"
}
},
// Tells Serilog to log stuff to a DataDog instance
{
// This name is important! It must be precisely this to work!
"Name": "DatadogLogs",
// The configuration properties here must all be written precisely as the following are
"Args": {
// Mandatory | API Key - Found in Datadog Organization/Api Keys section.
"apiKey": "6c...91",
// Optional | An arbitrary "source" that enables you to filter to your logs within the DataDog application
"source": "anything.you.want",
// Optional | An arbitrary "servive" that enables you to filter to your logs within the DataDog application
"service": "anything.you.want",
// Optional | An arbitrary "host" that enables you to filter to your logs within the DataDog application
"host": "anything.you.want",
// Optional | Arbitrary "tags" that enables you to filter to your logs within the DataDog application
"tags": [ "app.name:My.Tooling.Test" ],
// Optional | The default Datadog server is "intake.logs.datadoghq.com". If your DataDog instance is on the "app.datadoghq.com" URL, you do not need any of this configuration.
//
// | If you are not on the default Datadog server, you will need to find out what server you are on by visiting here and using the dropdown at the right https://docs.datadoghq.com/getting_started/site/
// | and then, once you know the server, you can visit here for the URL to use: https://docs.datadoghq.com/logs/log_collection/?tab=host#supported-endpoints
//
// | IMPORTANT: the URLs are not quite the entire URL that's needed. Be aware that "https://" will need to be placed on to determine which type you want to use. For example:
"configuration": {
"url": "https://http-intake.logs.datadoghq.eu",
"port": 443
}
}
}
],
// This ends up being stored in the final log message that is raised for you. You'll see it in DataDog under "properties" object where it mentions "Thread Id" or "SourceContext" for example.
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
// This ends up being stored in the final log message that is raised for you. You'll see it in DataDog under "properties" object where it mentions "Application".
"Properties": {
"Application": "My.Tooling.Test"
}
}
}
And specifically for c# apps, the following packages are required to be installed to use the above appsettings.json:
Mandatory stuff:
microsoft.extensions.configuration.json
serilog.aspnetcore
Sink types (The usings defined in appsettings.json):
serilog.sinks.datadog.logs
serilog.sinks.file
serilog.sinks.rollingfile
Enrichers that you've used:
serilog.enrichers.environment
serilog.enrichers.thread
serilog.settings.configuration
serilog.aspnetcore.enrichers.correlationid
Which can all be configured in C# like so (You have 2 choices):
// This allows you to add a Logging Provider to the already filled out list of logging providers
// that are supplied by default to your application.
builder.Services.AddLogging(loggingBuilder =>
{
// Get the builder's configuration from your Program
// (It essentially just gets the appsettings.json file)
ConfigurationManager configurationManager = builder.Configuration;
// Create a new LoggerConfiguration so that you can tell
// it to get its configuration from your appsettings.json file
Logger logger = new LoggerConfiguration()
.ReadFrom
.Configuration(configurationManager)
// Finally create the logger which will be used
.CreateLogger();
// Adds serilog to the logging providers
loggingBuilder.AddSerilog(logger);
});
OR
// Forces all logs to go through your single serilog configuration
// Be aware that if you use this, you need to ensure you configure your Serilog to
// do Console logging, otherwise you won't see any logs in the console.
// Luckily, I've provided all the code you need to do that in the appsettings.json configuration
// (But you may need to change the log level to Information or Debug for it to show up)
builder.Host.UseSerilog((hostingContext, services, loggerConfiguration) =>
{
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration);
});
And you can finally create logs by injecting the ILogger<YOURCLASSNAME> logger into the class where you want to use it and running the following commands:
logger.LogInformation("{message}", "Test");
logger.LogWarning("{message}", "Test");
logger.LogError("{message} {exception}", "Test", error);
logger.LogWarning(JsonConvert.SerializeObject(new Something() { Name = "Something", Description = "Something" }));

Serilog Expression Template in appSettings.json is being ignored

I am new to Serilog and am trying to use the Expression Template syntax within my appSettings.Development.json file.
In my Program.cs class I initialise the bootstrap logger from code. This works as expected, logging to the console with a 'normal' output template. Inside the Startup.cs class I re-setup the logger with ReadFrom.Configuration(...).CreateLogger().
If my configuration looks as follows, it works correctly and logs to the console using the specified outputTemplate:
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {EnvironmentName:u3} [{Level:u3}] {Message:lj} {Resource}{NewLine}{Exception}",
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console"
}
},...]
The Serilog "using" tag, common to the configuration, is:
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.Seq",
"Serilog.Expressions"
],
If I change the WriteTo tag to be as follows the log format is not honoured and the default template is used (the template configured with the bootstrap logger in fact):
"WriteTo": [
{
"Name": "Console",
"Args": {
"formatter": {
"type": "Serilog.Templates.ExpressionTemplate, Serilog.Expressions",
"template": "[{#t:HH:mm:ss} {#l:u3}{#if SourceContext is not null} ({SourceContext}){#end}] {#m}\n{#x}"
}
}
},...]
In trying to work out the solution I have looked at the question posed by mberube.net here but copying and pasting the code provided in that solution still doesn't log using the template format. My research to date indicates that the versions of the relevant Serilog packages I am using should be correct to enable this functionality.
My application is an ASP .Net Core Web API targetting net5.0. I have referenced Serilog.Expressions Version="3.4.0" and Serilog.Settings.Configuration Version="3.3.0".
I am hoping someone can assist me to understand why the templated output format is not being applied and what I can do to correct it?
If there is any further information that is required please let me know.
Thanks
The blocks in appsettings.Development.json files don't override the ones in appsettings.json - they're merged in, so what you're most likely ending up with is:
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {EnvironmentName:u3} [{Level:u3}] {Message:lj} {Resource}{NewLine}{Exception}",
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
"formatter": {
"type": "Serilog.Templates.ExpressionTemplate, Serilog.Expressions",
"template": "[{#t:HH:mm:ss} {#l:u3}{#if SourceContext is not null} ({SourceContext}){#end}] {#m}\n{#x}"
}
}
}
This won't play well with Serilog's configuration overload selection - it'll pick what it thinks is the simplest option among possible configuration methods.
A better idea is to have no sink configuration ("WriteTo" blocks) in the root appsettings.json file at all, and put separate configurations in appsettings.Development.json and appsettings.Production.json. It's very hard not to end up with unexpected results, otherwise.

Serilog not loading configuration?

I just got started with Serilog. I started out a very simple configuration, but I can't confirm it's loaded...maybe I am not looking into the right place?
appsettings (snippet):
"Serilog": {
"Using": [ "Serilog", "Serilog.Sinks.Console", "Serilog.Sinks.EventLog" ],
"MinimumLevel": {
"Default": "Debug"
}
program.cs
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(
(hostingContext, config) =>
configureConfiguration(hostingContext, config))
.UseSerilog(
(hostingContext, config) =>
configureSeriLog(hostingContext, config));
// local function
void configureSeriLog(HostBuilderContext cntxt, LoggerConfiguration builder)
{
builder.ReadFrom
.Configuration(cntxt.Configuration);
}
I set a breakpoint at the ReadFrom.Configuration() call. After the call is made, I look at the non-Public members _minimumLevel under the builder variable and it says Information. Am I looking at the wrong spot or the configuration wasn't loaded. Thanks a million!
To diagnose issues, you can try using the SelfLog
Serilog.Debugging.SelfLog.Enable(x => Debug.WriteLine(x));
Debugging and Diagnostics
When Serilog is not behaving as you expect, this may be caused by an
internal exception or configuration issue. Here are a couple of ways
to sort things out.
...

Azure durable functions Logs

I'm using a group of durable functions to do some critical backend logic and orchetration and I would like them to write logs in the same file so I can make a better analysis. Right know my I'm using injected ILog instance with the log.Information method but each function write its own log file.
I'm also using application insights but there is much more information in the files than app insight becauseof the telemetry sampling.
Here is an example of my host.json file
"version": "2.0",
"logging": {
"fileLoggingMode": "always",
"logLevel": {
"default": "Trace",
"Host": "Trace",
"Function": "Trace"
},
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"maxTelemetryItemsPerSecond": 20
}
}
},
Is there a way to have a single log file?
Thanks
How about a logging service that the functions can call? this would solve the problem of concurrent writes as only one service is editing the file. Secondly any new functions can just have the same logic added so it's quicker.

How to remove default serilog properties from log?

Using serilog to log a object, e.g. Log.Information("{#log}", log). Where log is a custom object.
The logs comes out like
{
"#t": "2020-01-24T09:31:23.5064000Z",
"#mt": "{#log}",
"log": {
"TraceId": "e57afecc-8efe-4d48-8057-d46cce71c3d9",
"Timestamp": "01/24/2020 09:31:23",
"Service": "serviceType",
"Action": "actionType",
"$type": "BaseLog"
}
}
I'd like not to have the extra serilog properties on there, and just have a flat structure of my log, e.g.
Even when i'm using CompactJsonFormatter
{
"TraceId": "e57afecc-8efe-4d48-8057-d46cce71c3d9",
"Timestamp": "01/24/2020 09:31:23",
"Service": "serviceType",
"Action": "actionType"
}
Is there an option/extension to serilog where I can remove these?
Do not put the burden of log transformation on your application, but you can use something like fluentd or logstash to do this for you. They are meant for doing those things.

Categories