引用命名空间:
using System.IO;
public class WriteLog
{
public static readonly WriteLog WriteLogInstance = new WriteLog();
public void Init(string filePath)
{
Init(filePath,string.Empty,0);
}
public void Init(string filePath,int maxSize_KB)
{
Init(filePath, string.Empty, maxSize_KB);
}
public void Init(string filePath,string fileName,int maxSize_KB)
{
_logFilePath = filePath;
_logFileName = fileName;
_logMaxSize = maxSize_KB;
}
private string _logFilePath;
public string LogFilePath
{
get
{
WriteLogInstance._logFilePath = string.IsNullOrEmpty(WriteLogInstance._logFilePath) ?
AppDomain.CurrentDomain.SetupInformation.ApplicationBase + System.IO.Path.DirectorySeparatorChar : WriteLogInstance._logFilePath;
return WriteLogInstance._logFilePath;
}
set { WriteLogInstance._logFilePath = value; }
}
private string _logFileName;
public string LogFileName
{
get
{
WriteLogInstance._logFileName = string.IsNullOrEmpty(WriteLogInstance._logFileName) ? "Applog.log" : WriteLogInstance._logFileName;
return WriteLogInstance._logFileName;
}
set { WriteLogInstance._logFileName = value; }
}
private int _logMaxSize;
/// <summary>
/// 日志文件大小,单位KB
/// 最大为5*1024KB,默认为1024KB。
/// </summary>
public int LogMaxSize
{
get
{
WriteLogInstance._logMaxSize = (WriteLogInstance._logMaxSize <= 0 || WriteLogInstance._logMaxSize > 5120) ? 1024 : WriteLogInstance._logMaxSize;
return WriteLogInstance._logMaxSize;
}
set { WriteLogInstance._logMaxSize = value; }
}
private object _objLock = new object();
public void WriteToLog(string[] content)
{
lock (_objLock)
{
string folder = LogFilePath;
string logFile = LogFileName;
string filePath = folder + logFile;
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
System.IO.FileInfo info = new System.IO.FileInfo(filePath);
if (info.Exists)
{
int maxSize = LogMaxSize*1024;//转换为字节
if (info.Length > maxSize)
{
string bkPath = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + logFile;
System.IO.File.Move(filePath, folder + bkPath);
}
}
System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath, true,System.Text.Encoding.UTF8);
foreach (string line in content)
{
writer.WriteLine(line);
}
writer.Close();
}
}
public void WriteToLog(string message)
{
string[] messages = new string[1] { message};
WriteToLog(messages);
}
public void WriteErrorInfo(string funcName, string message)
{
//写入本地log中。
List<string> messageList = new List<string>();
messageList.Add("--------------------------------------");
messageList.Add(System.DateTime.Now.ToString());
messageList.Add(funcName);
messageList.Add(message);
WriteLogInstance.WriteToLog(messageList.ToArray());
}
}
使用时:
首先可以:WriteLog.WriteLogInstance.Init(...);
然后:向日志中写信息,WriteLog.WriteLogInstance.WriteToLog(message);
或向日志中写异常信息:WriteLog.WriteLogInstance.WriteErrorInfo(...);