Gigi
Gigi

Reputation: 29441

How do you create a custom Akka .NET logger?

The Akka .NET documentation explains only how to configure custom loggers. How do you go about developing a custom logger in the first place?

Upvotes: 1

Views: 888

Answers (2)

Gigi
Gigi

Reputation: 29441

I've spent some time researching how to do this, and wrote up a detailed blog post about it.

In a nutshell, you need to handle five messages: Debug, Info, Warning, Error, and InitializeLogger.

public class MyLogger : ReceiveActor
{
    public MyLogger()
    {
        Receive<Debug>(e => this.Log(LogLevel.DebugLevel, e.ToString()));
        Receive<Info>(e => this.Log(LogLevel.InfoLevel, e.ToString()));
        Receive<Warning>(e => this.Log(LogLevel.WarningLevel, e.ToString()));
        Receive<Error>(e => this.Log(LogLevel.ErrorLevel, e.ToString()));
        Receive<InitializeLogger>(_ => Sender.Tell(new LoggerInitialized()));
    }

    // ...
}

The first four messages are self-explanatory if you've ever used logging before.

Log() is just a helper function defined by you, that handles the details of logging the message to destination.

InitializeLogger is done at startup. It is needed to notify the internal event bus that the logger has been set up and is ready to start receiving messages. You must reply with a LoggerInitialized message.

Ideally you should also take care of allocation and cleanup of external resources using the appropriate lifecyle hooks (PreStart() and PostStop()). Logging adapters out there don't currently do this yet.

Upvotes: 5

tomliversidge
tomliversidge

Reputation: 2369

Looks like you just need a regular Actor that overrides OnReceive(object message). Here is the default logger implementation:

https://github.com/akkadotnet/akka.net/blob/4acfa7c363bfa83ac71849a5a8487c8d6b1bbcb1/src/core/Akka/Event/DefaultLogger.cs

Here is the trace logger implementation:

https://github.com/akkadotnet/akka.net/blob/92177da15a7ef54e23b5224c05997592cbceb8e4/src/core/Akka/Event/TraceLogger.cs

Upvotes: 2

Related Questions