可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 :)
回答1:
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
回答2:
I would highly recommend looking at log4Net. This post covers the majority of what you need to get started.
回答3:
Another good logging library is NLog, which can log to a lot of different places, such as files, databases, event logger etc.
回答4:
I use The Object Guy's Logging Framework--as do most people who try it. This guy has some interesting comments about it.
回答5:
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.
回答6:
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);
回答7:
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.
回答8:
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);
回答9:
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.
回答10:
You can use built in .NET logging. Look into TraceSource and TraceListeners, they can be configured in the .config file.
回答11:
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.
回答12:
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.
回答13:
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.
回答14:
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.
回答15:
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