最近在项目中编写的log类,在博客上记录一下。
在调用的时候会按照当前时间自动生成对应的日志文件。代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace AutoUpdater_Client.Log
{
class LogOperator
{
#region 日志处理
#region 属性
private static string m_LogName = "Log_";
public static bool IsLogToFile = true;
public static string[] typeSet = {"ERROR", "UPDATE"};
#endregion
#region 变量
/// <summary>
/// 日志文件夹路径名称
/// </summary>
private static string m_LogDire = string.Empty;
#endregion
/// <summary>
/// 记录组件日志
/// </summary>
/// <param name="logInfo">日志内容</param>
public static void AddUpdateLog(string type, string logInfo)
{
try
{
if (!IsLogToFile)
{
// 不记录日志
return;
}
if (!typeSet.Contains(type))
type = "UNKNOWN";
m_LogDire = AppDomain.CurrentDomain.BaseDirectory.ToString() + "Log\\";
if (!Directory.Exists(m_LogDire))
{
// 不存在,创建
Directory.CreateDirectory(m_LogDire);
}
File.AppendAllText(m_LogDire + m_LogName + type + "_" + DateTime.Now.ToString("yyyyMMdd") + ".log",
System.DateTime.Now.ToString("HH:mm:ss:fff") + " " + logInfo + "\r\n",
Encoding.Default);
}
catch
{
}
}
#endregion
}
}
使用方法:
LogOperator.AddUpdateLog("UPDATE", "iVend process found, sending shuting down command");
因为是静态方法,所以直接用类名调用即可,之后即可看到文件: