简体   繁体   中英

Serilog format only the properties as json

If I have this:

logger.Information("this is a message with {property_name}", complexObject);

How can I make it equivalent to this:

logger.Information("this is a message with {property_name}", JsonConvert.SerializeObject(complexObject));

If a property name begins with @ then the whole object graph is stored in the event log.

logger.Information("this is a message with {@property_name}", complexObject);

If your sink records log events as JSON no extra work needed or it can be configured to do so. To emit JSON read Formatting JSON .

As per Mohsen's answer , in Serilog terms this is called Destructuring : the process of taking a complex .NET object and converting it into a structure, which may later be represented as say, a JSON object or XML blob.

Preserving Object Structure

There are many places where, given the capability, it makes sense to serialise a log event property as a structured object. DTOs (data transfer objects), messages, events and models are often best logged by breaking them down into properties with values.

For this task, Serilog provides the @ destructuring operator.

 var sensorInput = new { Latitude = 25, Longitude = 134 }; Log.Information("Processing {@SensorInput}", sensorInput);

('Destructuring' is a term borrowed from various programming languages; it is a style of pattern matching used to pull values out from structured data. The usage is Serilog is only notionally related at the moment, but possible future extensions to this operator could match the broader definition more accurately.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM