程序运行日志代码


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Utility
{
/// <summary>
/// 日记管理
/// </summary>
public class LogHelper
{
/// <summary>
/// 文件夹路径
/// </summary>
string Path = "";
static LogHelper _LogHelper = null;
object LockWrite = "LockWrite" as object;
/// <summary>
///
/// </summary>
public LogHelper()
{

}
/// <summary>
///
/// </summary>
/// <param name="_Path"> 文件夹路径</param>
public LogHelper(string _Path)
{
Path = _Path;
}
/// <summary>
/// 单实例
/// </summary>
public static LogHelper InstanctLogHelper
{
get
{
if (_LogHelper == null)
_LogHelper = new LogHelper();
return _LogHelper;

}
}

/// <summary>
/// 日记写入
/// </summary>
/// <param name="strMsg"></param>
public void WriteLog(string strMsg, string strFileName = "")
{
lock (LockWrite)
{
if (strFileName == "")
strFileName = "Log-" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
else
strFileName = strFileName + "-" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
System.IO.FileStream fs = null;
System.IO.StreamWriter m_streamWriter = null;
try
{
if (string.IsNullOrEmpty(Path))
{// 路径判断
if (string.IsNullOrEmpty(AppSetting.LogPath))
{ //读取配置信息
Path = AppSetting.GetAppPath+"\\log\\";
}
else
{// 读取程序路径
Path = AppSetting.LogPath;
}
}
if (!Directory.Exists(Path))
{// 不存在就创建
Directory.CreateDirectory(Path);
}

fs = new System.IO.FileStream(Path + strFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
m_streamWriter = new System.IO.StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End);
m_streamWriter.WriteLine(strMsg + ": " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "\n");
}
catch { }
finally
{ // 释放内存
if (m_streamWriter != null)
{
m_streamWriter.Flush();
m_streamWriter.Dispose();
}
if (fs != null)
{ fs.Dispose(); }
}
}
}
}

}

posted @ 2018-08-30 10:47  执念、旧时光  阅读(1138)  评论(0编辑  收藏  举报