serilog / serilog Goto Github PK
View Code? Open in Web Editor NEWSimple .NET logging with fully-structured events
Home Page: https://serilog.net
License: Apache License 2.0
Simple .NET logging with fully-structured events
Home Page: https://serilog.net
License: Apache License 2.0
E.g. for:
var silly = Console.Out;
Log.Information("A random {Silly} object", silly);
The sink will (probably :)) serialize the TextWriter
object, rather than convert it to a string
.
Expected behaviour in this case is that silly
will end up a string
in the document store.
Working on a possible solution - keeping @nickvane in the loop!
Intended as a more composable form of the lambda-based value transformations to allow properties to be excluded from custom types, e.g.
class MyClass
{
public int A { get; set; }
[NotLogged]
public Stream B { get; set; }
}
Please consider using HttpWorkerRequest.RequestTraceIdentifier (if available) instead of a newly-generated guid in the HttpRequestIdEnricher
.
This would allow the request to be correlated with ETW and other logging methods.
To get the API up and running, methods like ILogger.Information()
use params
arrays for message template parameters.
For lower GC overhead, overloads need to be created for up to three parameters, e.g. Information(string messageTemplate, object arg0, object ...)
.
Currently escaping , " and CRLF; at the very least CR and LF alone should also be escaped, some research/optimisation needed.
LoggerConfiguration may return a (disposable) Logger instead of ILogger, to avoid making ILogger itself disposable. Only the root logger should be disposable. Enrichers probably don't require disposal.
I.e. all current builds will have a 0.1.0.0 assembly version, until breaking changes occur, to prevent the need for cascading rebuilds, headaches etc.
The current assembly version will be recorded as AssemblyFileVersion.
E.g.:
log.Debug("The time is {0}", DateTime.Now.TimeOfDay);
Should produce:
Properties: { "0": "16:43..." }
I am using Serilog 0.9.3, and crafted a minimal example where the error occurs:
namespace ConsoleApplication5
{
using Serilog;
class Program
{
static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();
Log.Warning("{message}", "This is printed");
Log.Warning("{Message}", "This is NOT printed"); // Notice the capital M
}
}
}
Output:
09/12/2013 23:47:12 [Warning] "This is printed"
Expected output:
09/12/2013 23:47:12 [Warning] "This is printed"
09/12/2013 23:47:12 [Warning] "This is NOT printed"
Arbitrary filtering in pipeline.
Nick, this is more of a question and I will try this myself and explore the code, but in case it's not going to work, I'd like to log it here.
MongoDB replicaSet connection string support such as:
mongodb://server1/db/log,server2/db/log,server3/db/log
Thanks!
Raised in issue #15.
With more complex configurations, a representation (either debugger view, or textual dump) of the logger configuration including sinks, enrichers, filters, sub-loggers and so-on, would be a useful debugging aid.
I want to be able to pass in an object like HttpRequestMessage into log messages only store the information that is relevant - I also don't want to have extract the wanted information every time I write to the log as there would be a lot of duplicated code.
Also worth noting is that HttpRequestMessage as a property causes a StackOverflowException.
I'm thinking something like this (with a little more polish):
https://gist.github.com/sandcastle/5283376
Thoughts?
I.e. because some sinks batch or asynchronously process log events, the values attached as properties to those log events need to be immutable or thread-safe.
Serilog's built in array/dictionary/structure/scalar values achieve this already, however the preservation of arbitrary objects when passed as non-destructured parameters means that some mutable user types may change before serialisation in an async or batching sink.
To address this, unrecognised types need to be converted to strings immediately upon logging.
Currently, dictionaries are serialized as arrays of key-value pairs. To support more idiomatic JSON formatting some support for dictionaries-as-structures is needed. Recognising a subset of dictionaries (whose keys can form valid JSON property names) as StructureValues is probably the right way to go.
Needed before issue #30 will be elegantly addressable.
This happens for me with the latest pull in the Demo project.
Hi Folks,
I've been lurking around on this project for a while since I saw a pull request on Topshelf to integrate Serilog as the logging implementation.
This looks like a really useful library and I'm looking to integrate it into a solution that would require a new sink.
I'd like to forward log events over to Graylog2 via RabbitMQ (AMQP) (for various reasons, not the least of which is additional live monitoring events - message tap effectively) and would send it over in Gelf format.
(See that part at the top about how Gelf is designed to overcome the unstructured problem of standard logging? :-) )
I realize there is currently a Log4Net compatible "appender" that I could plumb in through the existing Log4Net sink. It seems like this guy has gotten fairly popular for his use of Graylog as an Enterprise Logging tool in accordance with Log4Net.
My question is this though, if I do that will I lose all of my structural log details in the process through the mapping of the Log4Net sink?
Anyone with any thoughts or input on the topic I'm all ears. :-)
I.e. filter by property value, filter by SourceContext (type)
I.e that writes to log4net, handling source types correctly.
We need to add .gitattributes with the following line to fix the line feed issue with git:
Courtesy Matt Ellis from the JetBrains team:
Hi Nick. Nice idea. And the good thing is, it’s close enough to the string formatting highlight that we can use the existing implementation as a guide to implement a plugin. You want to fire up dotPeek, point it at the ReSharper bin folder and find CSharpFormatItemAndMatchingArgumentContextHighlighter. This is the class that does the format string highlighting.
The only trouble is, it’s not easy to follow what’s going on. The class has an identifying attribute, and implements a static method to construct an async handler of some kind, but it’s really hard to see when it gets called and how often. I don’t have any experience with this, so I think the best thing to do would be to start to implement something and debug and see how far it goes. Essentially, it’s getting a data provider that can be used to get the current context – the abstract syntax tree of the current file, the currently selected element, the caret offset and selection and so on. It’s then looking for string literals to parse out of the string format, and applies a highlight to the currently selected format item and arguments, using a lifetime. This lifetime is a construct that allows an action to run when the lifetime is terminated – here it’s used to remove the highlight when the lifetime terminates, which will be when the cursor moves out of the way.
A different class is responsible for highlighting that an argument isn’t used, or that there aren’t enough arguments – FormatStringProblemAnalyzer. This class performs a number of checks and adds highlights for a number of conditions, including the mismatched arguments. You can reuse the highlight classes, but will have to implement your own ElementProblemAnalyzer.
http://msdn.microsoft.com/en-us/library/ee474552.aspx
Not exposed via TextWriter, so may require jumping through some extra hoops if deemed a worthwhile improvement.
See: FileSink.cs (43).
MessageTemplateRepository's cache grows unbounded, meaning that misuse of the message format (i.e. directly formatting in data) could cause OOM. A simple solution to this would be to limit the cache size, and simply degrade performance if the cache fills up.
A lot of features have been added/extended since the initial drop. There's possibly confusing terminology and a little bit of inconsistency creeping in. Before too much time passes, I'd like to review:
I***Factory
, IDestructuringPolicy
...)Core
, cleaner layout)Solution ->
In DumpFileSink constructor change:
_output = new StreamWriter(File.OpenWrite(path));
with:
_output = new StreamWriter(new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read));
Then it's possible to read the file in a texteditor.
As I am new to Git, and have not set it up, I ask kindly if anyone could change this?
BR
Hans Martin
hi,
this is so sweet library, thank you very much for it.
is there a way to create a chrome console sink ?
currently i am using this
https://chrome.google.com/webstore/detail/noaneddfkdjfnfdakjjmocngnfkfehhd
but it has big problem, it only logs once, and my need is for example if i am sending bulk emails in background, i want to see in Chrome console the logging status on each email sent.
thanks in advanced.
On Twitter you mentioned that it should be fairly straightforward to implement via IDestructuringPolicy
;)
In many cases I have an instance of Type.
It would be nice to have an overload that takes a type so i dont need to call
Serilog.Log.ForContext("SourceContext",type.FullName, false);
Which leaks implementation details
Should exceptions get logged? I am using this overload:
Log.ForContext().Error(
filterContext.Exception,
"Error caught in filter executing {RawUrl} for {User}",
filterContext.HttpContext.Request.RawUrl,
filterContext.HttpContext.User.Identity.Name);
The message is sent to the log file, but not the exception. Is this the expected behavior?
I have recently written a logging library that had many of the features serilog is working towards. The applications that used our library required very high perf and one of our favourite features was a a disposable timer that added timing properties to our log entries.
We found a lot of value in being able to include timings as log entry properties and because they were eventually stored in a database it was easy to run analytics over them to watch for trends in key parts of the system.
Below shows a simplified version of what our interfaces look like - while the builder pattern that we used may not fit this project, I'm sure parts could be adapted.
https://gist.github.com/sandcastle/5293291
Keen to hear your thoughts.
Currently a synchronous write per event, which is not expected to perform well under load. Keeping @robdmoore in the loop.
Strip core back to logging pipeline, with full Fx sinks and enrichers in a separate assembly.
Both can go in the same NUPKG when installed on full Fx.
Leaves open opportunities to use on phone/tablet.
If I configure an ILogger with a directory path that doesn't exist, ApplyRetentionPolicy throws an exception.
For example
.WriteTo.RollingFile(@".\Logs\log.log")
will throw an exception because the "Logs" directory doesn't exist.
A change inside RollingFileSink.cs OpenFile method fixes the issue:
_roller.GetLogFilePath(now, out path, out nextCheckpoint);
Directory.CreateDirectory(_roller.LogFileDirectory);
ApplyRetentionPolicy(path);
Particularly some mechanism to prevent RAM exhaustion if an infinite sequence is logged.
Binary data is most efficiently handled using Couch's attachments feature.
It would be a great addition to the MongoDB sink to allow it to automatically create capped collections if the 'log' collection does not already exist at the specified MongoUrl. You could also allow specifying the size of the capped collection.
This can of course be done manually, but would be very nice for Serilog to set this up for you based on passed sink parameters.
If a value is destructured that has cycles in its object graph, StackOverflowException
will be thrown. This is uncatchable so the guarantee of non-throwing ILogger
methods is broken.
As this can't be precomputed/cached on any basis, something simple and fast like a depth limit is probably sufficient. 100 values deep? ...
It would be possible to support .NET 4.0 by moving IObservable/IObserver to separate project, and removing dependencies to IReadOnlyList and IReadOnlyDictionary.
I'm forced (by corporate rules and a complaint) to downgrade a project to .NET 4.0 so I had to drop Serilog for now.
Be great to have a email Sink for Serilog.
Is there any way to tag a group of entries?
It will be nice to be able to add a tag while configuring the logger. This allows to easily filter the log entries that were recorded in a long running operation.
LoggerConfiguration
is growing and may be challenging to find methods in.
Instead of:
var log = new LoggerConfiguration()
.WithConsoleSink()
.EnrichedWithProperty("Foo", "Bar")
....
Why not:
var log = new LoggerConfiguration()
.WithSink.Console()
.Enriched.WithProperty("Foo", "Bar")
....
(Thanks Robert Wagner for the suggestion).
Hello,
I'm writing Common.Logging<=>Serilog bridge, and it'd be useful to construct LogEvents directly. Currently MessageTemplate can only be constructed by MessageTemplateParser, while the bridge doesn't need any parsing.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.