Error logging in C# - c#

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 :)

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

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

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

I use The Object Guy's Logging Framework--as do most people who try it. 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...). I use it on just about every project I build.
Highly recommended.

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);

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.

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);

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.

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

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.

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.

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.

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.

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

Related

SonarQube: Log to Console

Is this rule applied to console applications? If yes, how can we log to the conosle then? Or why shouldn't you do it?
http://dist.sonarsource.com/plugins/csharp/rulesdoc/0.10.0-RC/S2228.html
You can disable this rule on Console Applications. Nevertheless, even for console applications, it can be a good idea to limit the number of Console.WriteLine() calls for instance to make it easier to later on change your application. For example, you don't want to see Console.* calls spread to the whole codebase, but see it perhaps contained in a single class. If that is the case, feel free to mark those issues as Won't Fix in SonarQube, to indicate that you have reviewed them and that they are expected and accepted.
you ca try to implement a sonar-project.properties file that would contain a sonar exclusions definition and you can exclude from Sonar scan the files containing console.log calls.
example:
sonar.exclusions=**/__tests__/**/*,**/*.js

How to test whether a given functional code unit (C#) does NOT create/write any files to disk?

Imagine there's a mission-critical process that'll be used in a business which handles sensitive information (think of Credit Card, social security, patient records...etc). I would think this unit ideally should do whatever it has to do on-the-fly, meaning it won't intentionally write files to disk containing sensitive information. The idea here is that if the computer that runs this process is compromised, no sensitive information can be leaked, at least not by means of files.
What approaches could be taken to, say, come up with a unit test that will fail if the unit under test tries to write any file to disk?
There is the FileSystemWatcher (http://www.c-sharpcorner.com/uploadfile/puranindia/filesystemwatcher-in-C-Sharp/) however this requires you to know a specific directory. In your case this probably isn't very helpful since the program could write anything to disk any where. This introduces a unique problem. However, I have also found something called Detours from Microsoft. This appears to intercept all native win32 api calls. http://research.microsoft.com/en-us/projects/detours/ The issue with this is that its kind of hard to test, and integrating it into unit testing will be a challenge.
When you have to treat your software as "untrusted" in the sense that you need to prove it doesn't do something, testing becomes a complex task that requires you to run them on very controlled environments. When hooking in to the Win32 API, you will be deluged with API calls that need to be processed quickly. This can result in unintentional side effects because the application is not running in a truly native environment.
My suggestion to you (having worked several years doing software testing for Pharma automation to the exacting standards of the FDA) is to create a controlled environment, eg a virtual machine, that has a known starting state. This can be accomplished by never actually saving vmdk changes to disk. You have to take a snapshot of the file system. You can do this by writing a C# app to enumerate all files on the virtual drive, getting their size, some timestamps and maybe even a hash of the file. This can be time consuming so you may want (or be able) to skip the hashing. Create some sort of report, easiest would be by dropping them in a CSV or XML export. You then run your software under normal circumstances for a set period of time. Once this is complete, you run a file system analysis again and compare the results. There are some good apps out there for comparing file contents (like WinMerge). When taking these snap shots, the best way to do it would be to mount the vmdk as a drive in the host OS. This will bypass any file locks the guest OS might have.
This method is time intensive but quite thorough. If you don't need something of this depth, you can use something like Process Monitor and write the output to a file and run a report against that. However in my work I would have to prove that Process Monitor shows all IO before I could use it which can be just as hard as the method I spoke of above.
Just my 2 cents.
UPDATE:
I've been thinking about it, and you might be able to achieve fairly reliable results if you remove all references to System.IO from your code. Write a library to wrap around System.IO that either does not implement a write method, or only implements one that also writes to a log file. In this case, you simply have to validate that every time a write occurs using your library, it gets logged. Then validate using reflection that you don't reference System.IO outside of this new wrapper library. Your tests can then simply look at this log file to make sure only approved writes are occurring. You could make use of a SQL Database instead of a flat log file to help avoid cases of tampering or contaminated results. This should be much easier to validate than trying to script a virtual machine setup like I described above. This, of course, all requires you to access to the source code of the "untrusted" application, although since you are unit testing it, I assume you do.
1st option:
Maybe you could use Code Access Security, but the "Deny" is obsolete in .NET 4 (but should works in previous version):
[FileIOPermission(SecurityAction.Deny)]
public class MyClass
{
...
}
You may reactivate this behavior in .NET 4 using NetFx40_LegacySecurityPolicy
2nd option:
reducing the level of privilege may also works, as I know that downloaded app can't write on the disk and must use a special storage area.
3rd option:
Remove any reference to System.IO and replace by an interface that your code must use to write data to disk.
Then write an implementation that use System.IO (in a separate project)
In the nunit test, mock this interface and throw an exception when a method id called.
Problem is to ensure any developers will not call System.IO anymore. You can try to do this by enforcing coding rules using FxCop (or other similar tools)

Custom logging in mixed-language environment

I'm tasked of introducing logging to a larger project. I have the following requirements:
Logging to the same file must be enabled from Visual Studio's C++ products, C# products, desktop apps, windows services, and more than one process should be able to write to a log file at once.
Format of logs is custom (semi-colon delimited fields, something like "custom_date;custom_time;the_rest;of_the_fields").
Log files have limit in size.
There's main .log file and older .bak file. .bak file is deleted when new .log file is created and current .log is renamed to .bak.
In one special case name of log files depends on time of creation. There are no multi-process writes in this case.
Now, I can roll my own implementation, but it would be really nice if there are ready made free libraries that satisfy all of the requirements. Does any one know of such libraries?
Many of your requirements (I think all but the language independence) are fulfilled by log4net
As you want to use several software components to use the logger I would suggest to write a windows service by yourself as it can be used by all types of your client software (C++, C#, ...)
Maybe you could simply write to the Event Log.
I would recommend NLog, meets most of your requirements
Use Microsoft's Enterprise Exception and Logging Application blocks. It satisfies all of your requirements. Everything is configurable using the web.config or app.config and allows the use of templates to record specific details. Also note that Microsoft has included a rolling type logger that will automatically start a new file based upon size or date/time. It's a complete package for any type of logging you want to do, MSMQ, SQL, flat file, windows event log, etc.
Log4Net can help you with your 2 and 3 point, for your 1,4 and 5 point i suggest you write a WebService that do all the work for writting in the logs, create, delete, etc.

Mercurial , writing hooks using a .NET api

Hi I am looking for examples of how to write Mercurial hooks in a .NET language, including how to setup .hg/hgr
I have used the "Mercurial.Net" Api, but the information in the Windows environment variables is a bit limited and returning error messages on the standard error channel does not appear to work. I guess I am doing something wrong.
I am using .Net for a number of reasons , one being to link up with other systems using WFC
EDIT The new version of Mercurial.Net makes writing hooks easier, see see http://mercurialnet.codeplex.com/discussions/261283
Create a "Windows Application" project (eg MyHook).
Add a reference to "Mercurial.Net" (you can use NuGet to make it easier http://nuget.org/List/Packages/Mercurial.Net).
In your main method, do whatever processing you want (eg retrieve the log and then the info on the last commit - see http://mercurialnet.codeplex.com/discussions/261283 for examples). You can add a MessageBox.Show(message) to check that the hook is indeed executed.
Compile your project.
Add the hook to your .hg/hgrc file (below is an example of a hook that will be executed after each commit, see https://www.mercurial-scm.org/wiki/Hook for more info, http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html for even more info):
[hooks]
commit.hook1 = "C:\path to file\MyHook.exe"
The next time you commit your hook should be executed.
Check http://docs.vkarlsen.no/Mercurial.Net/ to learn about the classes of Mercurial.Net.

Useful log pattern/format?

I want to create a log file in my program.
My log pattern should contain: Log type, Datetime, Thread Name, Method Name, Log detail.. etc...
Which log pattern do you suggest?
Does any accepted log pattern for this? For example "trace log pattern", "event log pattern" etc...
Use a logging library such as NLog or Log4Net Then you can tweak the layout & renderers all you want without changing code or recompiling, and have lots of other useful functionality as well (such as rolling logs, db/network/email appenders, filters, log levels etc).
A good comparison of some logging frameworks
I REALLY recommend using Log4net; it supports almost everything you'd possibly want to do, is almost freakishly robust, and very straightforward to put in place.
You can find it here.
Why don't you try a logging framework like Log4Net ? There are plenty of tutorials around...
The Microsoft Application Blocks have some very good boiler plate code you can start with. The Logging Application Block can be used by itself, with other MAB elements or simply as a starting point for rolling your own.

Categories