using System;
using System.Globalization;
using System.Text;
using System.IO;
using System.ComponentModel;
using System.Windows.Forms;
namespace EtheSoft.ExtOperations
{
///<summary>
///日志信息类型
///</summary>
public enum LogMessageType
{
///<summary>错误信息</summary>
[Description("错误信息")]
ErrorMessage,
///<summary>系统信息</summary>
[Description("系统信息")]
SystemMessage,
///<summary>用户信息</summary>
[Description("用户信息")]
UserMessage
}
///<summary>日志记录类</summary>
public class LogEvent
{
/// <summary>
/// 记录日志
/// </summary>
/// <param name="fileContent">日志的记录内容(追加)</param>
/// <param name="type">日志的消息类型</param>
/// <param name="filePath">日志的文件路径(如果路径不存在就自动创建)</param>
/// <returns>如果成功写入值!返回True,否则返回False</returns>
public static void WriteLog(string fileContent, LogMessageType type, string filePath = "")
{
if (string.IsNullOrEmpty(filePath))
{
filePath = Application.StartupPath + @"\Log\SystemAutoLog.log";
}
var fileConfig = new FileConfig(Application.StartupPath + @"\LogConfig\LogConfig.ini");
try
{
int logIndex;
if (!File.Exists(filePath))
{
string[] pathsplitlist = filePath.Split('\\');
string newpath = "";
for (int i = 0; i < pathsplitlist.Length; i++)
{
if (i < pathsplitlist.Length - 1)
{
newpath += pathsplitlist[i] + "\\";
if (!Directory.Exists(newpath))
{
Directory.CreateDirectory(newpath);
}
}
}
File.Create(filePath).Close();
}
if (!File.Exists(Application.StartupPath + @"\LogConfig\LogConfig.ini"))
{
Directory.CreateDirectory(Application.StartupPath + @"\LogConfig");
File.Create(Application.StartupPath + @"\LogConfig\LogConfig.ini").Close();
}
try
{
logIndex =
int.Parse(fileConfig.ReadProfile("LogFileInfo", "FileName"));
filePath = fileConfig.ReadProfile("LogFileInfo", "FilePath");
}
catch
{
fileConfig.WriteProfile("LogFileInfo", "FilePath", filePath);
fileConfig.WriteProfile("LogFileInfo", "FileName", "0");
logIndex =
int.Parse(fileConfig.ReadProfile("LogFileInfo", "FileName"));
filePath = fileConfig.ReadProfile("LogFileInfo", "FilePath");
}
using (var sr = new StreamReader(filePath, Encoding.Default))
{
string content = null;
while (sr.Peek() != -1)
{
content += sr.ReadLine() + "\n";
}
sr.Close();
if (content != null)
{
if (content.Length >= 102400)
{
string path = filePath.Split('.')[0] + (logIndex + 1) + ".log";
File.Create(path).Close();
fileConfig.WriteProfile("LogFileInfo", "FilePath", path);
fileConfig.WriteProfile("LogFileInfo", "FileName", (logIndex + 1) + "");
}
}
}
using (var sw = new StreamWriter(filePath, true))
{
string message;
if (type == LogMessageType.ErrorMessage)
{
message = "错误信息";
}
else if (type == LogMessageType.SystemMessage)
{
message = "系统信息";
}
else
{
message = "用户信息";
}
sw.WriteLine("【" + message + "】");
sw.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture));
sw.WriteLine(fileContent);
sw.Flush();
sw.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
C# 日志操作类
最新推荐文章于 2024-07-22 18:23:10 发布