using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Web;
namespace Com.AppCode.Helper
{
/// <summary>
/// 日志记录到本地文件
/// </summary>
public class Log
{
/// <summary>
/// 调试日志
/// </summary>
/// <param name="msg"></param>
static public void Debug(
object msg)
{
WriteLog("Debug",
string.Empty, msg);
}
/// <summary>
/// 错误或异常日志
/// </summary>
/// <param name="msg"></param>
static public void Error(
object msg)
{
WriteLog("Error",
string.Empty, msg);
}
/// <summary>
/// 内容日志
/// </summary>
/// <param name="msg"></param>
static public void Info(
object msg)
{
WriteLog("Info",
string.Empty, msg);
}
/// <summary>
/// 警告日志
/// </summary>
/// <param name="msg"></param>
static public void Warn(
object msg)
{
WriteLog("Warn",
string.Empty, msg);
}
/// <summary>
/// 微信日志
/// </summary>
static public void Mp(
object msg)
{
WriteLog("Mp",
string.Empty, msg);
}
static private Mutex m_Mutex =
new Mutex();
/// <summary>
/// 日志文件记录
/// </summary>
/// <param name="errorType">日志类型</param>
/// <param name="pre">文件前缀可不填写</param>
/// <param name="msg">日志内容</param>
static public void WriteLog(
object errorType,
object pre,
object msg)
{
try
{
m_Mutex.WaitOne();
}
catch (Exception)
{
return;
}
try
{
string dir =
"/log/" + errorType +
"/";
string dirPath =
HttpContext.Current.Server.MapPath(dir);
if (!
Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
string fileName = pre + DateTime.Today.ToString(
"yyyyMMdd") +
".log";
string logPath =
Path.Combine(dirPath, fileName);
if (!
File.Exists(logPath))
{
File.Create(logPath).Close();
}
TextWriter oWrite =
File.AppendText(logPath);
string sTime = DateTime.Now.ToString(
"yyyy-MM-dd HH:mm:ss ffff");
oWrite.WriteLine(sTime +
": " +
msg);
oWrite.Close();
}
catch (Exception e)
{
EventLog myLog =
new EventLog();
myLog.Source =
"Com.Log";
myLog.WriteEntry("Write Log Error:" + msg +
"\t" +
e.Message);
}
finally
{
m_Mutex.ReleaseMutex();
}
}
}
}
转载请注明原文地址: https://mac.8miu.com/read-494267.html