Copy Code code as follows:
Using System;
Using System.IO;
Using System.Text;
public class Loginfo
{
private string errorinfo_user = ""; Log user custom error messages
private string errorposition = ""; Log error location information, including classes, functions, etc.
private string Errorinfo_sys = ""; Log system-generated exception error messages
Log information logging
public void Recorderrorinfo (string Position, String Error_sys, String error_user)
{
Errorposition = Position;
Errorinfo_sys = Error_sys;
Errorinfo_user = Error_user;
}
Custom log Information Format
private String Getlogcontent ()
{
string logcontent = "\ r \ n--------------------------------------------------------------------------\ r \ NAND";
Logcontent + = "[Custom Exception Log] [" + DateTime.Now.ToString () + "]\r\n";
Logcontent + + "=>[position]=>[" + errorposition + "]\r\n";
Logcontent + + "=>[userinfo]=>[" + Errorinfo_user + "]\r\n";
Logcontent + + "=>[sysinfo]=>[" + Errorinfo_sys + "]\r\n";
Logcontent + = "--------------------------------------------------------------------------\ r \ n";
return logcontent;
}
Save log information to file
public void Savelogtofile ()
{
Try
{
Get the file path of the log.
String FileName = @ "Log/loginfo_" + DateTime.Now.ToString ("yyyy-mm-dd") + ". txt";
Get the content of the log.
String logcontent = Getlogcontent ();
Create the stream of the log file and save the log.
FileStream Smlog = new FileStream (FileName, Filemode.append, FileAccess.Write);
If the stream is correct.
if (Smlog!= null)
{
Long Lfilecontentlen = smlog.length;
Smlog.lock (0, Lfilecontentlen);
byte[] buffer = encoding.getencoding ("gb2312"). GetBytes (logcontent);
Smlog.write (buffer, 0, buffer. Length);
Smlog.unlock (0, Lfilecontentlen);
Smlog.flush ();
Smlog.close ();
}
}
Catch
{ }
}
}
public class Logexample
{
Private Loginfo _log = new Loginfo ();
A handler function a
public void Function_first ()
{
Try
{
Do something which could is occur exception.
}
catch (Exception error)
{
_log.recorderrorinfo ("function Function_first", error.) Message.tostring (), "an exception occurs when the function Function_first is executed!" ");
_log.savelogtofile ();
}
}
A handler function two
public void Function_second ()
{
Try
{
Do something which could is occur exception.
}
catch (Exception error)
{
_log.recorderrorinfo ("function Function_second", error.) Message.tostring (), "an exception occurs when the function Function_second is executed!" ");
_log.savelogtofile ();
}
}
}
Class Program
{
static void Main (string[] args)
{
Create an object with built-in logs
Logexample Le = new Logexample ();
Perform a processing operation
Le.function_first ();
Perform processing operations two
Le.function_second ();
}
}