C# Class SimpleLogger.SimpleLog

Simple logging class
Just write to a file using static methods. By default, the file is named e.g. "2013_04_21.log" and is written to the current working directory. This class does not depend on anything. It can be used 'out of the box', no configuration necessary. To keep it simple, it contains just the most essential features like - Possibility to customize log directory and file name, SetLogFile - Possibility to pass log entry severity (Info, Warning, Error, Exception), Log(string, Severity, bool, int) - Convenience methods Info, Warning, Error to log with respective severity - Log exceptions, recursively with all inner exceptions, data, stack trace and specific properties of some exception types, Log(Exception, bool, int) - Basic, very simple log level filtering, LogLevel. - Automatically log source, i.e. class and method name where log method was called from (IMHO a very useful feature), GetCaller - Log is formatted as an XML fragment, one XML tag per entry. There's a method GetLogFileAsXml(System.DateTime) to complete the XML and get the file as an XML document. - There is a method ShowLogFile(DateTime) to display a log file in the browser. Method ShowLogFile() shows the current log file. - To improve speed, instead of writing each entry to the file immediately, by default, it is passed to a queue and being dequeued and written to disk in a background task. Unfortunately, this makes the class a bit more complicated. - Thread safety. This class can be used from different threads that all write to the same file. The task ID is logged in each item. This way, one can separate afterwards, which thread logged what. - New: Possibility to log directly to disk, without using the background task (thread). See argument "useBackgroundTask" in e.g. Info or Warning: - New: Possibility to start logging (i.e. the background task) explicitly as opposed to be started automatically on first log. See StartExplicitly for details.
Show file Open project: rudi-bruchez/SQLTrismegiste

Public Methods

Method Description
Check ( string message = "Test entry to see if logging works." ) : Exception

Check if logging to FileName works

Writes a test entry directly to FileName without using the background task. When no exception is returned, logging to FileName works.

ClearQueue ( ) : void

Clear background task's log entry queue. I.e. remove all log messages waiting to be written to FileName by the background task.

Error ( string message, bool useBackgroundTask = true ) : Exception

Write error message to log

Flush ( ) : void

Wait for all entries having been written to the file

GetExceptionAsXmlString ( Exception ex ) : string

Gets an XML string with detailed information about an exception

Recursively adds elements for inner exceptions. For the most inner exception, the stack trace is added. Tags for Exception.Data are added. Specific properties of the exception types SqlException, COMException and AggregateException are recognized, too.

GetExceptionXElement ( Exception ex ) : System.Xml.Linq.XElement

Gets an XElement for an exception

Recursively adds elements for inner exceptions. For the most inner exception, the stack trace is added. Tags for Exception.Data are added. Specific properties of the exception types SqlException, COMException and AggregateException are recognized, too.

GetFileName ( System.DateTime dateTime ) : string

Gets the log filename for the passed date

GetLogFileAsText ( ) : string

Get the current log file as text document

Does not throw an exception when the log file does not exist.

GetLogFileAsText ( System.DateTime dateTime ) : string

Get the log file for the passed date as text document

Does not throw an exception when the log file does not exist.

GetLogFileAsXml ( ) : System.Xml.Linq.XDocument

Get the current log file as XML document

Does not throw an exception when the log file does not exist.

GetLogFileAsXml ( System.DateTime dateTime ) : System.Xml.Linq.XDocument

Get the log file for the passed date as XML document

Does not throw an exception when the log file does not exist.

Info ( string message, bool useBackgroundTask = true ) : Exception

Write info message to log

Log ( Exception ex, bool useBackgroundTask = true, int framesToSkip ) : Exception

Write exception to log

Log ( System.Xml.Linq.XElement xElement, Severity severity = Severity.Info, bool useBackgroundTask = true, int framesToSkip ) : Exception

Write XElement to log

Unless useBackgroundTask is set to false (default is true), the XElement is not actually written to the file here, but enqueued to the log entry queue. It is dequeued by WriteLogEntriesToFile in a backround task and actually written to the file there. This is much faster than writing directly to disk in the main thread (what is done when useBackgroundTask is set to false). However, writing to the file is synchronized between threads. I.e. writing directly can be done from multiple threads. Also, using the background task and writing directly to the file can be used both in parallel. When StartExplicitly is set to true (default is false), the background task must be started explicitly by calling StartLogging, to get messages actually written to the file. They get enqueued before the background task is started, though. I.e. they will get logged when the background task is started later. When StartExplicitly is set to false, which is the default, logging background task (thread) is started automatically when first calling this method with useBackgroundTask set to true (which is the default).

Log ( string message, Severity severity = Severity.Info, bool useBackgroundTask = true, int framesToSkip ) : Exception

Write message to log

See Log(XElement, Severity, bool, int).

LogFileExists ( System.DateTime dateTime ) : bool

Check, whether there is a log file for the passed date

SetLogDir ( string logDir, bool createIfNotExisting = false ) : Exception

Set new logging directory

SetLogFile ( string logDir = null, string prefix = null, string suffix = null, string extension = null, string dateFormat = null, Severity logLevel = null, bool startExplicitly = null, bool check = true, bool writeText = null, string textSeparator = null ) : Exception

Set all log properties at once

Set all log customizing properties at once. This is a pure convenience function. All parameters are optional. When logDir is set and it cannot be created or writing a first entry fails, no exception is thrown, but the previous directory, respectively the default directory (the current working directory), is used instead.

ShowLogFile ( ) : void

Shows the current log file

Opens the default program to show XML files and displays the requested file, if it exists. Does nothing otherwise. A temporary XML file is created and saved in the users's temporary path each time this method is called. So don't use it excessively.

ShowLogFile ( System.DateTime dateTime ) : void

Show a log file for the passed date

Opens the default program to show text or XML files and displays the requested file, if it exists. Does nothing otherwise. When WriteText is false, a temporary XML file is created and saved in the users's temporary path each time this method is called. So don't use it excessively in that case. Otherwise, the log file itself is shown.

StartLogging ( ) : void

Start logging

Start background task pointing to WriteLogEntriesToFile to write log files to disk. Is called automatically by Enqueue when the first entry is logged, unless StartExplicitly is set to true (default is false). Then, this method has to be called explicitly to start logging.

StopLogging ( bool flush = true ) : void

Stop logging background task, i.e. logging at all.

Stop background task pointing to WriteLogEntriesToFile to write log files to disk.

Warning ( string message, bool useBackgroundTask = true ) : Exception

Write warning message to log

Private Methods

Method Description
ConvertXmlToPlainText ( System.Xml.Linq.XElement xmlEntry ) : string

Convert xmlEntry to plain text to be written to a file.

A typical xml entry to be converted looks like this: Entering method. See Source which method is meant. Something went wrong. Object reference not set to an instance of an object. at SimpleLogDemo.Program.DoSomethingElse(String fred) in D:\Projekt\VisualStudio\SimpleLogDemo\SimpleLogDemo\Program.cs:line 91 ]]> This is a basic implementation so far. Feel free to implement your own if you need something more sophisticated, e.g. nicer exception formatting.

CurrentDomainProcessExit ( object sender, EventArgs e ) : void

Process is about to exit

This is some kind of static destructor used to flush unwritten log entries.

Dequeue ( ) : void

Dequeue log entry

Enqueue ( System.Xml.Linq.XElement logEntry ) : void

Enqueue log entry to be written to log file

When StartExplicitly is set to false (which is the default), logging is started automatically by calling StartLogging from inside this method when the first logEntry is enqueued. When StartExplicitly is set to true, logEntry is just enqueued, but not yet actually written to the log file. The latter will be done when StartLogging is called explicitly.

GetCaller ( int framesToSkip ) : string

Detects the method that was calling the log method

The method is walking up the frames in the stack trace until the first method outside SimpleLog is reached. When log calls to SimpleLog are wrapped in an application, this may still not be the method where logging was called initially (e.g. when an exception occurred and has been logged). In that case set framesToSkip accordingly to get outside the wrapper method(s).

Peek ( ) : System.Xml.Linq.XElement

Get the next log entry from the queue, but do not dequeue it

SimpleLog ( ) : System

Static constructor

WriteLogEntriesToFile ( ) : void

Write log entries to the file on disk

The thread looks every 100 milliseconds for new items in the queue.

WriteLogEntryToFile ( System.Xml.Linq.XElement xmlEntry ) : Exception

Write one log entry to file

This method can be called from the logging background thread or directly from the main thread. Lock accordingly to avoid multiple threads concurrently accessing the file. When the lock can not be got within five seconds, xmlEntry is not being written to the file, but a respective exception is returned, saying what went wrong.

Method Details

Check() public static method

Check if logging to FileName works
Writes a test entry directly to FileName without using the background task. When no exception is returned, logging to FileName works.
public static Check ( string message = "Test entry to see if logging works." ) : Exception
message string Test message to write to the log file
return System.Exception

ClearQueue() public static method

Clear background task's log entry queue. I.e. remove all log messages waiting to be written to FileName by the background task.
public static ClearQueue ( ) : void
return void

Error() public static method

Write error message to log
public static Error ( string message, bool useBackgroundTask = true ) : Exception
message string The message to write to the log
useBackgroundTask bool Whether to use the background task (thread) to write messages to disk. Default is true. This is much faster than writing directly to disk in the main thread.
return System.Exception

Flush() public static method

Wait for all entries having been written to the file
public static Flush ( ) : void
return void

GetExceptionAsXmlString() public static method

Gets an XML string with detailed information about an exception
Recursively adds elements for inner exceptions. For the most inner exception, the stack trace is added. Tags for Exception.Data are added. Specific properties of the exception types SqlException, COMException and AggregateException are recognized, too.
public static GetExceptionAsXmlString ( Exception ex ) : string
ex System.Exception The exception to get detailed information about
return string

GetExceptionXElement() public static method

Gets an XElement for an exception
Recursively adds elements for inner exceptions. For the most inner exception, the stack trace is added. Tags for Exception.Data are added. Specific properties of the exception types SqlException, COMException and AggregateException are recognized, too.
public static GetExceptionXElement ( Exception ex ) : System.Xml.Linq.XElement
ex System.Exception The exception to get the XElement for
return System.Xml.Linq.XElement

GetFileName() public static method

Gets the log filename for the passed date
public static GetFileName ( System.DateTime dateTime ) : string
dateTime System.DateTime The date to get the log file name for
return string

GetLogFileAsText() public static method

Get the current log file as text document
Does not throw an exception when the log file does not exist.
public static GetLogFileAsText ( ) : string
return string

GetLogFileAsText() public static method

Get the log file for the passed date as text document
Does not throw an exception when the log file does not exist.
public static GetLogFileAsText ( System.DateTime dateTime ) : string
dateTime System.DateTime The date and time to get the log file for. Use DateTime.Now to get the current log file.
return string

GetLogFileAsXml() public static method

Get the current log file as XML document
Does not throw an exception when the log file does not exist.
public static GetLogFileAsXml ( ) : System.Xml.Linq.XDocument
return System.Xml.Linq.XDocument

GetLogFileAsXml() public static method

Get the log file for the passed date as XML document
Does not throw an exception when the log file does not exist.
public static GetLogFileAsXml ( System.DateTime dateTime ) : System.Xml.Linq.XDocument
dateTime System.DateTime The date and time to get the log file for. Use DateTime.Now to get the current log file.
return System.Xml.Linq.XDocument

Info() public static method

Write info message to log
public static Info ( string message, bool useBackgroundTask = true ) : Exception
message string The message to write to the log
useBackgroundTask bool Whether to use the background task (thread) to write messages to disk. Default is true. This is much faster than writing directly to disk in the main thread.
return System.Exception

Log() public static method

Write exception to log
public static Log ( Exception ex, bool useBackgroundTask = true, int framesToSkip ) : Exception
ex System.Exception The exception to write to the log
useBackgroundTask bool Whether to use the background task (thread) to write messages to disk. Default is true. This is much faster than writing directly to disk in the main thread.
framesToSkip int How many frames to skip when detecting the calling method, . This is useful when log calls to are wrapped in an application. Default is 0.
return System.Exception

Log() public static method

Write XElement to log
Unless useBackgroundTask is set to false (default is true), the XElement is not actually written to the file here, but enqueued to the log entry queue. It is dequeued by WriteLogEntriesToFile in a backround task and actually written to the file there. This is much faster than writing directly to disk in the main thread (what is done when useBackgroundTask is set to false). However, writing to the file is synchronized between threads. I.e. writing directly can be done from multiple threads. Also, using the background task and writing directly to the file can be used both in parallel. When StartExplicitly is set to true (default is false), the background task must be started explicitly by calling StartLogging, to get messages actually written to the file. They get enqueued before the background task is started, though. I.e. they will get logged when the background task is started later. When StartExplicitly is set to false, which is the default, logging background task (thread) is started automatically when first calling this method with useBackgroundTask set to true (which is the default).
public static Log ( System.Xml.Linq.XElement xElement, Severity severity = Severity.Info, bool useBackgroundTask = true, int framesToSkip ) : Exception
xElement System.Xml.Linq.XElement The XElement to log
severity Severity Log entry severity, defaults to
useBackgroundTask bool Whether to use the background task (thread) to write messages to disk. Default is true. This is much faster than writing directly to disk in the main thread.
framesToSkip int How many frames to skip when detecting the calling method, . This is useful when log calls to are wrapped in an application. Default is 0.
return System.Exception

Log() public static method

Write message to log
See Log(XElement, Severity, bool, int).
public static Log ( string message, Severity severity = Severity.Info, bool useBackgroundTask = true, int framesToSkip ) : Exception
message string The message to write to the log
severity Severity Log entry severity
useBackgroundTask bool Whether to use the background task (thread) to write messages to disk. Default is true. This is much faster than writing directly to disk in the main thread.
framesToSkip int How many frames to skip when detecting the calling method, . This is useful when log calls to are wrapped in an application. Default is 0.
return System.Exception

LogFileExists() public static method

Check, whether there is a log file for the passed date
public static LogFileExists ( System.DateTime dateTime ) : bool
dateTime System.DateTime The date and time to check the existance of a log file for
return bool

SetLogDir() public static method

Set new logging directory
public static SetLogDir ( string logDir, bool createIfNotExisting = false ) : Exception
logDir string The logging diretory to set. When passing null or the empty string, the current working directory is used.
createIfNotExisting bool Try to create directory if not existing. Default is false.
return System.Exception

SetLogFile() public static method

Set all log properties at once
Set all log customizing properties at once. This is a pure convenience function. All parameters are optional. When logDir is set and it cannot be created or writing a first entry fails, no exception is thrown, but the previous directory, respectively the default directory (the current working directory), is used instead.
public static SetLogFile ( string logDir = null, string prefix = null, string suffix = null, string extension = null, string dateFormat = null, Severity logLevel = null, bool startExplicitly = null, bool check = true, bool writeText = null, string textSeparator = null ) : Exception
logDir string for details. When null is passed here, is not set. Here, is created, when it does not exist.
prefix string for details. When null is passed here, is not set.
suffix string for details. When null is passed here, is not set.
extension string for details. When null is passed here, is not set.
dateFormat string for details. When null is passed here, is not set.
logLevel Severity for details. When null is passed here, is not set.
startExplicitly bool for details. When null is passed here, is not set.
check bool Whether to call , i.e. whether to write a test entry after setting the new log file. If true, the result of is returned.
writeText bool for details. When null is passed here, is not set.
textSeparator string for details. When null is passed here, is not set.
return System.Exception

ShowLogFile() public static method

Shows the current log file
Opens the default program to show XML files and displays the requested file, if it exists. Does nothing otherwise. A temporary XML file is created and saved in the users's temporary path each time this method is called. So don't use it excessively.
public static ShowLogFile ( ) : void
return void

ShowLogFile() public static method

Show a log file for the passed date
Opens the default program to show text or XML files and displays the requested file, if it exists. Does nothing otherwise. When WriteText is false, a temporary XML file is created and saved in the users's temporary path each time this method is called. So don't use it excessively in that case. Otherwise, the log file itself is shown.
public static ShowLogFile ( System.DateTime dateTime ) : void
dateTime System.DateTime The date and time to show the log file for.
return void

StartLogging() public static method

Start logging
Start background task pointing to WriteLogEntriesToFile to write log files to disk. Is called automatically by Enqueue when the first entry is logged, unless StartExplicitly is set to true (default is false). Then, this method has to be called explicitly to start logging.
public static StartLogging ( ) : void
return void

StopLogging() public static method

Stop logging background task, i.e. logging at all.
Stop background task pointing to WriteLogEntriesToFile to write log files to disk.
public static StopLogging ( bool flush = true ) : void
flush bool Whether to write all pending entries to disk before. Default is true.
return void

Warning() public static method

Write warning message to log
public static Warning ( string message, bool useBackgroundTask = true ) : Exception
message string The message to write to the log
useBackgroundTask bool Whether to use the background task (thread) to write messages to disk. Default is true. This is much faster than writing directly to disk in the main thread.
return System.Exception