Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serialize objects or collections to log

Tags:

c#

.net

nlog

I want save some addtitional info with my error message. For example it should be user query, or something else. How should I do it?

Is there any build it methods for logging collections, structurest or objects? Or I should serialize it myself?

like image 456
Yavanosta Avatar asked Apr 11 '14 08:04

Yavanosta


People also ask

When should we use serialization?

Usually used in Hibernate, JMS, JPA, and EJB, serialization in Java helps transport the code from one JVM to another and then de-serialize it there. Deserialization is the exact opposite process of serialization where the byte data type stream is converted back to an object in the memory.

Why do we need to serialize objects?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed.

Why do we serialize objects in C#?

Serialization in C# is the process of converting an object into a stream of bytes to store the object to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

Why do we serialize objects in Java?

Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage. Deserialization is the process of converting Object stream to actual Java Object to be used in our program.


2 Answers

NLog ver. 4.5 includes new features for structured logging:

var order = new Order
{
    OrderId = 2,
    Status = OrderStatus.Processing
};

logger.Info("Test {value1}", order);
// object Result:  Test MyProgram.Program+Order
logger.Info("Test {@value1}", order);
// object Result:  Test {"OrderId":2, "Status":"Processing"}
logger.Info("Test {value1}", new { OrderId = 2, Status = "Processing"});
// anomynous object. Result: Test { OrderId = 2, Status = Processing }
logger.Info("Test {@value1}", new { OrderId = 2, Status = "Processing"});
// anomynous object. Result:Test {"OrderId":2, "Status":"Processing"}

https://github.com/NLog/NLog/wiki/How-to-use-structured-logging

like image 105
Rolf Kristensen Avatar answered Nov 12 '22 15:11

Rolf Kristensen


there is a very simple solution to implement structure logging with nlog.

try
            {
                // bla bla bla 
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "MyRequest{@0}", request);

            }

the symbol @ serialize the request object

https://github.com/NLog/NLog/wiki/How-to-use-structured-logging

like image 20
dimmits Avatar answered Nov 12 '22 14:11

dimmits