区分 log4net 输出中的源上下文
我对 log4net 相当陌生,我似乎找不到任何明确的示例来说明如何处理这种情况。
我有一个由三层组成的通信堆栈:硬件、传输和协议。 这三个层包含在管理器类中。 就代码的用户而言,他们创建具有硬件类型(串行、以太网、SSL 等)的管理器并提供地址。 可以有多个管理器实例,每个实例连接到不同的目标。
我希望我的输出能够给出特定消息来自哪个连接的上下文(127.0.0.1 或 COM5 等)。 ThreadContext 没有多大用处,因为管理器可以从任何线程调用,并且每个层都在自己的线程上运行。
有没有办法根据对象的特定实例设置上下文? 或者有更好的方法来处理输出格式吗?
I'm fairly new to log4net, and I can't seem to find any clear examples of how to handle this situation.
I have a communication stack that consists of three layers: hardware, transport, and protocol. The three layers are contained inside of a manager class. As far as the user of the code is concerned they create the manager with a hardware type (Serial,Ethernet,SSL,etc) and provide an address. There can be multiple manager instances, each connecting to a different target.
I'd like my output to give context of which connection the particular message came from (127.0.0.1 or COM5 etc). The ThreadContext isn't much use because the manager can be called from any thread and each layer runs on its own thread.
Is there any way to set a context based on a particular instance of an object? Or is there a better way to handle the output formatting?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加额外的每消息上下文的一种方法是不仅记录字符串消息,而且创建您自己的消息对象,其中包含日志信息和连接硬件类型(以及您想要包含的任何其他信息)。
您可以找到这样的示例
另一种选择是使用嵌套诊断上下文:
NDC 数据将包含在消息中,并且可以使用 %ndc 模式输出。 但需要注意的是,NDC 将包含在其使用范围内记录的任何消息中,这也许就是您考虑采用自定义消息路由的原因。
A way of adding additional per-message context is to not only log a string message but create your own message object containing both log information and the connection hardware type (and any additional information you would like to include).
You can find an example of this here.
Another option could be using a Nested Diagnostics Context:
The NDC data will be included with the message and can be output with the %ndc pattern. A note of warning though, the NDC will be included with ANY messages logged within its using scope, which is perhaps why you would consider going the custom message route.
您应该使用采用
字符串名称
的LogManager.GetLogger()
重载,这样您就可以传递几乎任何内容作为记录器名称。You should use an overload of
LogManager.GetLogger()
that takesstring name
, this way you can pass pretty much anything as the logger name.