-
Notifications
You must be signed in to change notification settings - Fork 0
SeriLog
Kota edited this page Sep 24, 2018
·
13 revisions
- Serilog provides diagnostic logging to files, the console, and elsewhere
-
SeriLog: Basic configurations of SeriLog
-
Sinks: Which helps in storing the logs into specific type of storage systems
- Serilog.Sinks.Console
- Serilog.Sinks.ColoredConsole
- Serilog.Sinks.File
- Serilog.Sinks.RollingFile
-
Basic Settings
var template = "{Timestamp:yyyy-MMM-dd HH:mm::ss} [{Level}] {Message}{NewLine}{Exception}";
var _logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.ColoredConsole(Serilog.Events.LogEventLevel.Verbose, outputTemplate: template)
.WriteTo.File("log.txt")
.WriteTo.RollingFile("rollinglogfile.txt", retainedFileCountLimit: 2)
.CreateLogger();
Log.Logger = _logger;
Log.Logger.Information("Log Message");
-
Scalar Data: Boolean, Int (byte <=> decimal), String, DateTime, Others (GUID, URI, nullables)
-
Collections, Objects, Dictionary<key, value> (key must be Scalar),
-
Simple Scalar values
// String, Int, DateTime, GUID
Log.Information("Added user {UserName}, Age {UserAge}, DOB {BirthDate} - ID {_id}",
_name, _age, _birthDate, GUID.NewGUID);
// output: Added user "Kota", Age 99, DOB 05/20/2018 01:01:01 - 616165sda1sd-asfjwqafaw-sfa
- Collections and Objects
// LIST
var _colors = new List<string> { "red", "blue", "green" };
Log.Information("Basic Colors - {Colors}", _colors)
// Output: Basic Colors - ["red", "blue", "green"]
// DICTIONARY
var _countryCodes = new Dictionary<string, int> { {"India",91 }, {"UK",44 } };
Log.Information("Country Codes - {CountryCodes}", _countryCodes)
// Output: Country Codes - [ ("India": 91 ), ("UK": 44) ]
// OBJECT
class Color {
public string Red {get; set;}
public string Green {get; set;}
public string Blue{get; set;}
public override string ToString()
{
return string.Format("R:{0} G:{1} B:{2}", Red, Green, Blue)
}
}
var headerColor = new Color{ Red=100, Green=0, Blue=50 };
Log.Information("Header Color - {HeaderColor}", headerColor)
//Output: Header Color - namespace.Color -> It calls ToString() of Color object. So overwrite ToString() of Color class
//output: Header Color - "R:100 G:0 B:50"
// this stores the data in the form of string and not objects
- Destructured Objects (@ - Destructuring operator)
// from the example above - now serilog saves the whole object (not string)
Log.Information("Header Color - {@HeaderColor}", headerColor)
//output: Header Color - Color { Red:100, Green:0, Blue:50 }
// To log only few properties and not all - change Config
Log.Logger = new LoggerConfiguration()
.Destructure.ByTransforming<Color>(x=> new {x.Red, x.Green})
.WriteTo.Console().CreateLogger();
Log.Information("Header Color - {@HeaderColor}", headerColor)
//output: Header Color - Color { Red:100, Green:0 }
- Are place where we can store messages. Ex: Azure Table Storage, Colored/Console, Rolling/File, Elastic Search, ElmahIO, Log4Net, MongoDb, MS SQL Server, Seq, RavenDB, Trace, Win Events etc..
// add RavenDB Sink
var logDocumentStore = new DocumentStore{ Url="http://localhost:8080", Defaultdatabase = "log" }
logDocumentStore.Initialize();
var _logger = new LoggerConfiguration()
.WriteTo.RavenDB(logDocumentStore)
.CreateLogger();
Log.Logger = _logger;
userToAdd = new User { name ="sda", Age = 21 }
Log.Information("Added user {@NewUser}", userToAdd);
// output: http://localhost:8080/raven/studio.html
- Formatting
// STRING
Log.Information("Added {username}, name")
// Added "Kota"
Log.Information("Added {username:l}, name")
// Added Kota
// NUMBER
Log.Information("PI is {pi}, Math.PI")
// PI is 3.14159265358979
Log.Information("PI is {pi:0.00}, Math.PI")
// PI is 3.14 ==> storage will still have all decimals
-
Levels (verbose, Debug, Information, Warning, Error, Fatal)
- Configuring minimum level (default Information)
Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Console().CreateLogger();- Sink Specific
Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information) .WriteTo.File("verboselog.txt", restrictedToMinimumLevel: LogEventLevel.Verbose) .CreateLogger();- Adding Logging Context
var contextLogger = Log.Logger.ForContext<Program>(); contextLogger.Information(); // output: "SourceContext": "namespace.Program" Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .Filter.ByExcluding(x => x.properties.ContainsKey("CommandLineArguements")) .CreateLogger(); Log.Information("Params {CommandLineArguements}", args); // will not be logged // some more .Filter.ByExcluding(Matching.WithProperty("CommandLineArguements")) // same as above .Filter.ByIncludingOnly(x => x.MessageTemplate.Text.Contains("Attempting to divide")) .Filter.ByExcluding(Matching.FromSource<Program>()) .Filter.ByExcluding(Matching.FromSource("ConsoleApplication"))- Correlating Log Entries
- Adding property for all log entries
Log.Logger = new LoggerConfiguration() .Enrich.WithProperty("ApplicationName", "SampleApp") .WriteTo.Console() .CreateLogger();- Adding Custom Enricher
class ApplicationDetailsEnricher { public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { var applicationAssemblyName = Assembly.GetEntryAssembly().GetName() logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("ApplicationName", applicationAssemblyName.Name)) logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("ApplicationVersion", applicationAssemblyName.Version)) } } Log.Logger = new LoggerConfiguration() .Enrich.With(new ApplicationDetailsEnricher()) .WriteTo.Console() .CreateLogger();
-
Extras
- Serilog.Extras.Appsettings : Gives us ability to use application configuration files for setting up Serilog
- App.Config , Web.Config
- Configure Minimum Logging Level, Add Sinks, Configure Sink Properties
- Either Code Configuration OR AppSettings
- Serilog.Extras.Web
- Enriches HttpRequestId, HttpRequestNumber, HttpRequestTraceId, HttpSessionId, UserName
- custom HttpModule: Current Url & method, optionally store posted form data, Log unhandled exceptions
- Serilog.Extras.Timing
- Timed Operations Log Events
- [Information] Beginning...
- [Information] Completed...
- [Warning] Took longer than expected...
- Available Properties
- TimedOperationId
- TimedOperationDescription
- TimedOperationElapsed
- Timed Operations Log Events
- Serilog.Extras.Appsettings : Gives us ability to use application configuration files for setting up Serilog
-
By default, If we configure wrong we don't get any message but the logger doesn't work
// setup file
Serilog.Debugging.SelfLog.Out = Console.Out;
Seq - A log server
- Creates DB and web server (browser interface)
- Requirements: .NET Framework 4.5 | Win 7 SP1+ / Win Server 2008 R2 SP1+
- Go to https://getseq.net/ install and you are done
- Start browsing http://localhost:5341
- Default log store path C:\ProgramData\Seq\ (Data | Logs)
- Seq.Client.Serilog
.WriteTo.Seq("http://localhost:5341")