C# 中记录错误

发布于 2024-07-06 21:00:22 字数 516 浏览 5 评论 0原文

我正在从 C++ 编码切换到 C#。 我需要用 C# 中类似的东西替换我的 C++ 错误记录/报告宏系统。

在我的 C++ 源代码中,我可以编写

LOGERR("Some error"); 或者 LOGERR("输入 %s 和 %d 出错", stringvar, intvar);

宏观与 然后,支持库代码将(可能是可变参数)格式化的消息与源文件、源行、用户名和时间一起传递到数据库中。 相同的数据也被填充到数据结构中以便稍后向用户报告。

有人有 C# 代码片段或指向执行此基本错误报告/日志记录的示例的指针吗?

编辑:当我问这个问题时,我对 .NET 还很陌生,并且不知道 System.Diagnostics.Trace。 System.Diagnostics.Trace 正是我当时所需要的。 从那时起,我在日志记录要求更大、更复杂的项目中使用了 log4net。 只需编辑 500 行 XML 配置文件,log4net 就会完成您需要的一切:)

I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#.

In my C++ source I can write

LOGERR("Some error");
or
LOGERR("Error with inputs %s and %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. 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?

Edit: At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

一直在等你来 2024-07-13 21:00:22

这里有很多 log4net 拥护者,所以我确信这会被忽略,但我将添加我自己的偏好:

System.Diagnostics.Trace

这包括侦听 Trace() 方法的侦听器,然后写入日志文件/输出窗口/事件日志,框架中包含的有 DefaultTraceListenerTextWriterTraceListenerEventLogTraceListener。 它允许您指定级别(警告、错误、信息)和类别。

MSDN 上的跟踪类
写入 Web 应用程序中的事件日志
UdpTraceListener - 将 log4net 兼容的 XML 消息写入日志查看器,例如作为 log2console

Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference:

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. It allows you to specify levels (Warning,Error,Info) and categories.

Trace class on MSDN
Writing to the Event Log in a Web Application
UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console

慢慢从新开始 2024-07-13 21:00:22

我强烈建议您查看 log4Net。 这篇帖子涵盖了您需要获得的大部分内容开始了。

I would highly recommend looking at log4Net. This post covers the majority of what you need to get started.

静若繁花 2024-07-13 21:00:22

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

Another good logging library is NLog, which can log to a lot of different places, such as files, databases, event logger etc.

只想待在家 2024-07-13 21:00:22

我使用Object Guy 的日志框架——大多数尝试它的人也是如此。 这个人对此有一些有趣的评论

I use The Object Guy's Logging Framework--as do most people who try it. This guy has some interesting comments about it.

以歌曲疗慰 2024-07-13 21:00:22

企业库log4net 并且它还提供了许多其他功能(缓存、异常处理、验证等)。 我几乎在我构建的每个项目中都使用它。

强烈推荐。

Enterprise Library is a solid alternative to log4net and it offers a bunch of other capabilities as well (caching, exception handling, validation, etc...). I use it on just about every project I build.

Highly recommended.

忘东忘西忘不掉你 2024-07-13 21:00:22

尽管我个人讨厌它,但 log4net 似乎是 C# 日志记录的事实上的标准。 使用示例:

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

Even though I personally hate it, log4net seems to be the de facto standard for C# logging. Sample usage:

log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error(“Some error”);
log.ErrorFormat("Error with inputs {0} and {1}", stringvar, intvar);
晨曦÷微暖 2024-07-13 21:00:22

正如我在另一个线程中所说,我们一直在多个生产应用程序中使用 Object Guy 的日志框架几年。 它非常易于使用和扩展。

As I said in another thread, we've been using The Object Guy's Logging Framework in multiple production apps for several years. It's super easy to use and extend.

屌丝范 2024-07-13 21:00:22

Log4Net 是一个相当全面的日志框架,它允许您记录到不同的级别(调试、错误、 Fatal)并将这些日志语句输出到可能不同的地方(滚动文件、Web 服务、Windows 错误)

我可以通过创建记录器实例

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

然后记录错误来轻松记录任何地方。

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

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)

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);
初见你 2024-07-13 21:00:22

Serilog 虽然迟到了,但它带来了一些有趣的选择。 它看起来很像经典的基于文本的记录器:

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

但是,与早期的框架不同,它仅在写入文本(例如写入文件或控制台)时将消息和参数呈现为字符串。

这个想法是,如果您使用“NoSQL”样式的数据存储来存储日志,则可以记录如下事件:

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

.NET 格式字符串语法已扩展,因此您可以将上面的示例编写为:

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

在这种情况下,属性将是称为 Name(而不是 0),使查询和关联更容易。

已经有一些不错的存储选项。 MongoDB 和 Azure 表存储似乎很受 DIY 欢迎。 我最初构建了 Serilog(尽管它是一个社区项目),现在我正在开发一个名为 Seq 的产品,它提供存储以及查询这些类型的结构化日志事件。

Serilog is late to the party here, but brings some interesting options to the table. 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, e.g. 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:

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

The .NET format string syntax is extended so you can write the above example as:

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

In this case the property will be called Name (rather than 0), making querying and correlation easier.

There are already a few good options for storage. MongoDB and Azure Table Storage seem to be quite popular for 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.

骷髅 2024-07-13 21:00:22

您可以使用内置的 .NET 日志记录。 查看 TraceSource 和 TraceListeners,它们可以在 .config 文件中配置。

You can use built in .NET logging. Look into TraceSource and TraceListeners, they can be configured in the .config file.

苯莒 2024-07-13 21:00:22

log4net 也是如此。 我添加这两位是因为对于实际使用来说,查看一些开源实现以查看带有一些方便添加的真实世界代码示例是有意义的。 对于 log4net,我建议立即查看 subtext。 特别要查看应用程序启动和程序集信息位。

Ditto for 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. Particularly take a look at the application start and assemblyinfo bits.

极度宠爱 2024-07-13 21:00:22

除了有关使用 System.Diagnostics 方法进行日志记录的几条评论之外,我还想指出 DebugView 工具非常简洁,可以在需要时检查调试输出 - 除非您需要它,否则应用程序不需要生成日志文件,您只需启动 DebugView 即可需要的时候。

Further to the couple of comments realting to the use of the System.Diagnostics methods for logging, I would also like to point out that the DebugView tool is very neat for checking debug output when needed - unless you require it, there is no need for the apps to produce a log file, you just launch DebugView as and when needed.

锦欢 2024-07-13 21:00:22

System.Diagnostics 中的内置跟踪在 .NET Framework 中表现良好,我在许多应用程序中使用它。 然而,我仍然使用 log4net 的主要原因之一是内置的 .NET Framework 跟踪缺少 log4net 已经内置的许多有用的全功能附加程序。

例如,确实没有定义好的滚动文件跟踪侦听器.NET Framework,而不是 VB.NET dll 中的框架,后者实际上功能并不全。

根据您的开发环境,我建议使用 log4net,除非第 3 方工具不可用,然后我会说使用 System.Diagnostics 跟踪类。 如果您确实需要更好的附加程序/跟踪侦听器,您始终可以自己实现它。

例如,我们的许多客户要求我们在其公司计算机上安装时不使用开源库,因此在这种情况下,.NET Framework 跟踪类非常适合。

另外 - http://www.postsharp.org/ 是一个我正在研究的 AOP 库,可能会还可以帮助进行日志记录,如代码项目所示:http://www.codeproject .com/KB/dotnet/log4postsharp-intro.aspx

The built in tracing in System.Diagnostics is fine in the .NET Framework and I use it on many applications. 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.

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.

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. If you really need a better appender/tracelistener you can always implement it yourself.

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.

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.

假面具 2024-07-13 21:00:22

ExceptionLess 是可用于日志记录的最简单的 nuget 包之一。 它是一个开源项目。 它会自动处理未处理的异常,并且可以使用手动日志选项。 您可以在线登录或本地服务器上的自托管

ExceptionLess is one of the easiest nuget package available to use for logging. 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.

败给现实 2024-07-13 21:00:22

正如其他人所说,Log4Net 相当常见,并且与 Log4j 类似,如果您曾经使用过 Java,它将对您有所帮助。

您还可以选择使用日志应用程序块 http://www.codeproject.com /KB/architecture/GetStartedLoggingBlock.aspx

Log4Net, as others have said, is fairly common and similar to Log4j which will help you if you ever do any Java.

You also have the option of using the Logging Application Block http://www.codeproject.com/KB/architecture/GetStartedLoggingBlock.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文