Sending logs to DataDog using a Serilog sink not working - c#

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

Related

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.

Populate custom columns in Serilog MsSql sink

I am using Serilog in my dotnet core application. I have added custom columns to the default list of columns provided by Serilog. Below is how my "Serilog" configuration looks like in appsettings.json file -
"Serilog": {
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"connectionString": <connectionString>
"tableName": "Log",
"autoCreateSqlTable": true,
"columnOptionsSection": {
"removeStandardColumns": [ "MessageTemplate", "Properties"], //remove the Properties column in the standard ones
"customColumns": [
{
"ColumnName": "ControllerName",
"DataType": "varchar",
"DataLength": 50
}
]
},
"timeStamp": {
"columnName": "Timestamp",
"convertToUtc": true
}
}
}
]
}
So I have removed "MessageTemplate" and "Properties" from the default list of columns created by Serilog and added "ControllerName" as a new column to the table Log, where Serilog logs its data. What i want is that when I am logging information , I want to provide value to the "ControllerName" column. How can it be done?
I have found the below solution :
_logger.LogInformation("{ControllerName}{Message}", "TestController", "Starting up..");
This line of code provides value to the ControllerName column, but the message column gets the value as
"TestController""Starting up.."
I want the message column to get value as
Starting up..
It seems you are using Microsoft's ILogger<T> instead of Serilog's ILogger thus in order to add a contextual property that will be included in your log event without being part of the message, you have to create a new logging scope using BeginScope e.g.
using (_logger.BeginScope("{ControllerName}", nameof(TestController)))
{
_logger.LogInformation("{Message}", "Starting up...");
}
Another alternative is to add a property to Serilog's LogContext:
using (LogContext.PushProperty("ControllerName", nameof(TestController))
{
_logger.LogInformation("{Message}", "Starting up...");
}
This will give you the same end result as with BeginScope above, but is a Serilog-specific API and kind of defeats the purpose of using ILogger<T> in the first place, so BeginScope would be preferred unless you decide to use Serilog's ILogger instead.
One important observation is that in order for the LogContext to work, you need to enable it when you configure your logger. For example:
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext() // <<<<<<<<<<#############
.WriteTo.Console()
.CreateLogger();
If you were to use Serilog's ILogger, then in addition to be able to use the LogContext you can alternatively create a new context using Log.ForContext:
var contextLogger = logger.ForContext("ControllerName", nameof(TestController));
contextLogger.Information("{Message}", "Starting up...");
ps: If you're not sure whether you should use Microsoft's ILogger<T> or Serilog's ILogger, I recommend reading this answer: Serilog DI in ASP.NET Core, which ILogger interface to inject?

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.

Using EventFlow to monitor ETW event on local machine

I am trying to set up a simple ETW and EventFlow example that allows specific ETW providers to be monitored. In this case the Service Control Manager ETW provider to monitor when Service Start and Stop messages are issued.
I have the following input configuration for Tracing and ETW.
"inputs": [
{
"type": "Trace",
"traceLevel": "Warning"
},
{
"type": "ETW",
"providers": [
{
"providerName": "Service Control Manager"
}
]
}]
I have the following code which is starting up monitoring using EventFlow.
static void Main(string[] args)
{
using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json"))
{
System.Diagnostics.Trace.TraceWarning("EventFlow is working!");
Console.ReadLine();
}
}
The trace event is appearing in the console, but when I start and stop a service no ETW events are appearing.
Is EventFlow designed for this scenario on a local machine? If so what am i missing in my configuration or code?
The console process is running as administrator and the account has access to the Performance Log Users and Performance Log Monitors group
If you want to listen for ETW events from the Service Control Manager, you'll need to listen for the provider named Microsoft-Windows-Services.
Here is what I have in my eventFlowConfig.json
{
"inputs": [
{
"type": "ETW",
"providers": [
{ "providerName": "Microsoft-Windows-Services" }
]
}
],
"filters": [],
"outputs": [
{ "type": "StdOutput" }
],
"schemaVersion": "2016-08-11",
"extensions": []
}
To check that it worked, I stopped and started SQL Server services. The events were output in the console as expected.
As an additional sanity check, you can use the Visual Studio Diagnostic Events viewer to listen for ETW events. Launch the viewer, click the cog to configure, add the provider name in the list of ETW Providers, and apply. You should now be able to see the same events in both the viewer and your console application.

Categories