如何创建自定义 Akka .NET 记录器?
How do you create a custom Akka .NET logger?
Akka .NET 文档仅解释了如何 configure custom loggers。首先,您如何着手开发自定义记录器?
看起来您只需要一个覆盖 OnReceive(object message) 的常规 Actor。这是默认的记录器实现:
这是跟踪记录器的实现:
我花了一些时间研究如何做到这一点,并写了一篇详细的blog post。
简而言之,您需要处理五个消息:Debug
、Info
、Warning
、Error
和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()));
}
// ...
}
如果您以前使用过日志记录,那么前四个消息是不言自明的。
Log()
只是您定义的辅助函数,用于处理将消息记录到目标的详细信息。
InitializeLogger
在启动时完成。需要通知内部事件总线记录器已设置并准备好开始接收消息。您必须回复 LoggerInitialized
消息。
理想情况下,您还应该使用适当的生命周期挂钩(PreStart()
和 PostStop()
)处理外部资源的分配和清理。在那里记录适配器目前还没有这样做。
Akka .NET 文档仅解释了如何 configure custom loggers。首先,您如何着手开发自定义记录器?
看起来您只需要一个覆盖 OnReceive(object message) 的常规 Actor。这是默认的记录器实现:
这是跟踪记录器的实现:
我花了一些时间研究如何做到这一点,并写了一篇详细的blog post。
简而言之,您需要处理五个消息:Debug
、Info
、Warning
、Error
和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()));
}
// ...
}
如果您以前使用过日志记录,那么前四个消息是不言自明的。
Log()
只是您定义的辅助函数,用于处理将消息记录到目标的详细信息。
InitializeLogger
在启动时完成。需要通知内部事件总线记录器已设置并准备好开始接收消息。您必须回复 LoggerInitialized
消息。
理想情况下,您还应该使用适当的生命周期挂钩(PreStart()
和 PostStop()
)处理外部资源的分配和清理。在那里记录适配器目前还没有这样做。