3

How can I get structured logging when using e.g. Serilog with Servicestack?

The examples from both Serilog and NLog have the form Log.Information("Hello World from {FirstName}", "Thomas"); for which I cannot find a matching method signature in ServiceStack.

4
  • 1
    There is DebugFormat, InfoFormat, WarnFormat and ErrorFormat Commented Jun 7, 2020 at 20:02
  • @RolfKristensen how do they work? Would log.PushProperty("FirstName", "Thomas") then log.InfoFormat("Hello World from {FirstName}"); work? So I'd need to write two lines? Commented Jun 8, 2020 at 14:03
  • @speciman You asked for something that matched Log.Information. If you want something that matches Log.PushProperty then you should update your question. Commented Jun 8, 2020 at 15:52
  • @RolfKristensen - I did not see the xxxFormat methods in the docs, that got me confused. They are just what I was looking for. Commented Jun 9, 2020 at 10:18

1 Answer 1

3

See logging docs for enhanced Serilog Logging APIs whilst this existing StackOverflow answer shows a Serilog Enrichers example.

SerilogLoggerTests.cs shows different examples of using Serilog:

var log = new SerilogLogger(GetType());

const string message = "Error Message";
const string messageFormat = "Message Format: message: {0}, exception: {1}";

var ex = new Exception();
log.Info(message);
log.Info(message, ex);
log.InfoFormat(messageFormat, message, ex.Message);
log.Info(ex, messageFormat, messageFormat, ex);

and a Log Context example with custom properties:

var log = new SerilogLogger(new LoggerConfiguration()
    .WriteTo.Sink(sink).CreateLogger());

var messageTemplate = "Testing adding {prop2} props";
log.ForContext("prop", "value").InfoFormat(messageTemplate, "awesome");

There's also PushProperty() APIs to assign custom properties, see Serilog's Enrichment docs for examples.

Sign up to request clarification or add additional context in comments.

3 Comments

Already saw the docs, but did not understand. It seems they all need an exception to work, e.g. ILog.Info(Exception ex, string messageTemplate, params object[] propertyValues). I don't have an exception, just want to log template + params. Can I pass null as the first param?
@specimen there are different overloads you can use, see updated answer.
I did not see the xxxFormat methods in the docs, that got me confused. They are just what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.