简体   繁体   English

登录C#时出错

[英]Error logging in C#

I am making my switch from coding in C++ to C#. 我正在从C ++编码切换到C#。 I need to replace my C++ error logging/reporting macro system with something similar in C#. 我需要用C#中类似的东西替换我的C ++错误日志/报告宏系统。

In my C++ source I can write 在我的C ++源代码中,我可以写

LOGERR("Some error"); LOGERR(“有些错误”); or LOGERR("Error with inputs %s and %d", stringvar, intvar); 或LOGERR(“输入%s和%d出错”,stringvar,intvar);

The macro & supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. 宏和支持库代码然后将(可能是varargs)格式化的消息与源文件,源代码行,用户名和时间一起传递到数据库中。 The same data is also stuffed into a data structure for later reporting to the user. 相同的数据也被填充到数据结构中,以便稍后向用户报告。

Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging? 有没有人有C#代码片段或指向执行此基本错误报告/日志记录的示例的指针?

Edit: At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. 编辑:当我问这个问题时,我对.NET很陌生,并且不知道System.Diagnostics.Trace。 System.Diagnostics.Trace was what I needed at that time. System.Diagnostics.Trace是我当时需要的。 Since then I have used log4net on projects where the logging requirements were larger and more complex. 从那以后,我在日志记录要求更大,更复杂的项目中使用了log4net。 Just edit that 500 line XML configuration file and log4net will do everything you will ever need :) 只需编辑500行XML配置文件,log4net即可完成您需要的所有内容:)

Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference: 很多log4net都支持这里,所以我相信这会被忽略,但我会添加自己的偏好:

System.Diagnostics.Trace

This includes listeners that listen for your Trace() methods, and then write to a log file/output window/event log, ones in the framework that are included are DefaultTraceListener , TextWriterTraceListener and the EventLogTraceListener . 这包括侦听Trace()方法的侦听器,然后写入日志文件/输出窗口/事件日志,框架中包含的是DefaultTraceListenerTextWriterTraceListenerEventLogTraceListener It allows you to specify levels (Warning,Error,Info) and categories. 它允许您指定级别(警告,错误,信息)和类别。

Trace class on MSDN MSDN上的跟踪类
Writing to the Event Log in a Web Application 写入Web应用程序中的事件日志
UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console UdpTraceListener - 将log4net兼容的XML消息写入日志查看器,例如log2console

I would highly recommend looking at log4Net . 我强烈推荐查看log4Net This post covers the majority of what you need to get started. 这篇文章涵盖了入门所需的大部分内容。

另一个好的日志库是NLog ,可以登录到很多不同的地方,比如文件,数据库,事件记录器等。

I use The Object Guy's Logging Framework --as do most people who try it. 我使用The Object Guy的Logging Framework - 对大多数尝试它的人都这样做。 This guy has some interesting comments about it. 这家伙有一些有趣的评论

Enterprise Library is a solid alternative to log4net and it offers a bunch of other capabilities as well (caching, exception handling, validation, etc...). Enterprise Librarylog4net的可靠替代品,它还提供了许多其他功能(缓存,异常处理,验证等)。 I use it on just about every project I build. 我几乎在我构建的每个项目中使用它。

Highly recommended. 强烈推荐。

As I said in another thread, we've been using The Object Guy's Logging Framework in multiple production apps for several years. 正如我在另一个帖子中所说,我们多年来一直在多个生产应用程序中使用The Object Guy的Logging Framework It's super easy to use and extend. 它非常易于使用和扩展。

Even though I personally hate it, log4net seems to be the de facto standard for C# logging. 即使我个人讨厌它, log4net似乎也是C#日志记录的事实标准。 Sample usage: 样品用法:

log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error(“Some error”);
log.ErrorFormat("Error with inputs {0} and {1}", stringvar, intvar);

Log4Net is a rather comprehensive logging framework that will allow you to log to different levels (Debug, Error, Fatal) and output these log statements to may different places (rolling file, web service, windows errors) Log4Net是一个相当全面的日志框架,它允许您登录到不同的级别(Debug,Error,Fatal)并将这些日志语句输出到不同的位置(滚动文件,Web服务,Windows错误)

I am able to easily log anywhere by creating an instance of the logger 通过创建记录器的实例,我可以轻松地在任何地方进行记录

private static readonly ILog _log = LogManager.GetLogger(typeof([Class Name]));

and then logging the error. 然后记录错误。

_log.Error("Error messsage", ex);

Serilog is late to the party here, but brings some interesting options to the table. Serilog在这里参加派对的时间很晚,但却带来了一些有趣的选择。 It looks much like classical text-based loggers to use: 它看起来很像基于文本的经典记录器:

Log.Information("Hello, {0}", username);

But, unlike earlier frameworks, it only renders the message and arguments into a string when writing text, eg to a file or the console. 但是,与早期的框架不同,它只在将文本写入文件时将消息和参数呈现为字符串,例如文件或控制台。

The idea is that if you're using a 'NoSQL'-style data store for logs, you can record events like: 我们的想法是,如果您使用'NoSQL'风格的数据存储来存储日志,您可以记录以下事件:

{
    Timestamp: "2014-02-....",
    Message: "Hello, nblumhardt",
    Properties:
    {
        "0": "nblumhardt"
    }
}

The .NET format string syntax is extended so you can write the above example as: 扩展了.NET格式的字符串语法,因此您可以将上面的示例编写为:

Log.Information("Hello, {Name}", username);

In this case the property will be called Name (rather than 0 ), making querying and correlation easier. 在这种情况下,该属性将被称为Name (而不是0 ),使查询和关联更容易。

There are already a few good options for storage. 已经有一些很好的存储选择。 MongoDB and Azure Table Storage seem to be quite popular for DIY. MongoDB和Azure Table Storage似乎非常受DIY欢迎。 I originally built Serilog (though it is a community project) and I'm now working on a product called Seq , which provides storage and querying of these kinds of structured log events. 我最初构建了Serilog(虽然它是一个社区项目),我现在正在开发一种名为Seq的产品,它提供存储和查询这些结构化日志事件。

You can use built in .NET logging. 您可以使用内置的.NET日志记录。 Look into TraceSource and TraceListeners, they can be configured in the .config file. 查看TraceSource和TraceListeners,可以在.config文件中配置它们。

Ditto for log4net. 同样适用于log4net。 I'm adding my two bits because for actual use, it makes sense to look at some open source implementations to see real world code samples with some handy additions. 我正在添加我的两位,因为在实际使用中,查看一些开源实现以查看带有一些方便添加的真实世界代码示例是有意义的。 For log4net, I'd suggest off the top of my head looking at subtext . 对于log4net,我建议在脑海中寻找潜台词 Particularly take a look at the application start and assemblyinfo bits. 特别是看一下应用程序的start和assemblyinfo位。

对于使用System.Diagnostics方法进行日志记录的几点评论,我还要指出, DebugView工具非常适合在需要时检查调试输出 - 除非你需要它,否则不需要要生成日志文件的应用程序,您只需在需要时启动DebugView。

The built in tracing in System.Diagnostics is fine in the .NET Framework and I use it on many applications. System.Diagnostics中的内置跟踪在.NET Framework中很好,我在许多应用程序中使用它。 However, one of the primary reasons I still use log4net is that the built in .NET Framework tracing lacks many of the useful full featured appenders that log4net already supplies built in. 但是,我仍然使用log4net的主要原因之一是内置的.NET Framework跟踪缺少log4net已经内置的许多有用的全功能appender。

For instance there really isn't a good rolling file trace listener defined in the .NET Framework other than the one in a VB.NET dll which really is not all that full featured. 例如,在.NET Framework中定义的滚动文件跟踪侦听器确实没有在VB.NET dll中定义的那个,这实际上并不是全部功能。

Depending on your development environment I would recommend using log4net unless 3rd party tools are not available, then I'd say use the System.Diagnostics tracing classes. 根据您的开发环境,我建议使用log4net,除非第三方工具不可用,然后我会说使用System.Diagnostics跟踪类。 If you really need a better appender/tracelistener you can always implement it yourself. 如果你真的需要一个更好的appender / tracelistener,你可以自己实现它。

For instance many of our customers require that we do not use open source libraries when installed on their corporate machines, so in that case the .NET Framework tracing classes are a perfect fit. 例如,我们的许多客户要求我们在公司机器上安装时不使用开源库,因此在这种情况下,.NET Framework跟踪类非常适合。

Additionally - http://www.postsharp.org/ is an AOP library I'm looking into that may also assist in logging as demonstrated here on code project: http://www.codeproject.com/KB/dotnet/log4postsharp-intro.aspx . 另外 - http://www.postsharp.org/是我正在研究的AOP库,它也可以帮助记录,如代码项目所示: http//www.codeproject.com/KB/dotnet/log4postsharp- intro.aspx

ExceptionLess is one of the easiest nuget package available to use for logging. ExceptionLess是可用于日志记录的最简单的nuget包之一。 Its an open source project. 它是一个开源项目。 It automatically takes care of unhandled exception, and options for manually logs are available. 它会自动处理未处理的异常,并提供手动日志选项。 You can log to online or self host on local server. 您可以在本地服务器上登录在线或自托管

Log4Net, as others have said, is fairly common and similar to Log4j which will help you if you ever do any Java. 正如其他人所说,Log4Net相当普遍,类似于Log4j,如果您使用任何Java,它将对您有所帮助。

You also have the option of using the Logging Application Block http://www.codeproject.com/KB/architecture/GetStartedLoggingBlock.aspx 您还可以选择使用日志记录应用程序块http://www.codeproject.com/KB/architecture/GetStartedLoggingBlock.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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