Recently I made a small project on the c ++ server and wrote a simple log component. I translated it using c # Over the past two days, and it was much faster than c ++, share with you!
After the component runs, all the log information will be cached in a collection, and then a separate thread is responsible for writing the log information in the collection into a file.
The following functions are supported:
1. log information can be stored by level;
2. log files can be automatically replaced at the specified size;
3. Only log files of the last month are saved;
4. supports logging in multi-threaded environments;
In general, the functions are quite simple. The following is the component interface:
Using System;
Namespace Soar. Framework
{
/// <Summary>
/// Log component
/// </Summary>
Public interface ILogger
{
/// <Summary>
/// Start the log component
/// </Summary>
Bool Run ();
/// <Summary>
/// Start the log component
/// </Summary>
/// <Param name = "logLevel"> level </param>
/// <Param name = "logDirectory"> log file storage directory (for example, logs \) </param>
/// <Param name = "maxFileSize"> default size of a single log file (unit: MB) </param>
/// <Returns> </returns>
Bool Run (LogLevel logLevel, string logDirectory, int maxFileSize );
/// <Summary>
/// Obtain the currently set log record level
/// </Summary>
/// <Returns> </returns>
String GetLevel ();
/// <Summary>
/// Set the log record level
/// </Summary>
/// <Param name = "logLevel"> </param>
/// <Returns> </returns>
Bool SetLevel (LogLevel logLevel );
/// <Summary>
/// Record debugging information
/// </Summary>
/// <Param name = "msg"> </param>
Void Debug (string msg );
/// <Summary>
/// Record general information
/// </Summary>
/// <Param name = "msg"> </param>
Void Info (string msg );
/// <Summary>
/// Record warning information
/// </Summary>
/// <Param name = "msg"> </param>
Void Warn (string msg );
/// <Summary>
/// Record general error information
/// </Summary>
/// <Param name = "msg"> </param>
Void Error (string msg );
/// <Summary>
/// Record critical error information
/// </Summary>
/// <Param name = "msg"> </param>
Void Fatal (string msg );
}
}
For details about the call method, see the source code. Note the following when writing this log component:
Using Create. File to Create a File, this method returns a FileStream object, and this object will always occupy the File you created, so that you cannot operate on the File you created,
Therefore, you must manually release the returned object after creating the file.
If (! File. Exists (filePath ))
{
FileStream fs = File. Create (filePath );
Fs. Flush ();
Fs. Close ();
}