using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading; namespace Model
{
/// <summary>
/// 日志文件帮助类
/// </summary>
public class LogInfoHelper
{
#region Field
private static Object m_Lock = new object();
// 消息队列 (内部加锁访问)
private Queue<IGetWriteLogInfo> m_MessageQueue = new Queue<IGetWriteLogInfo>();
private Thread m_BackWriteThread;
private static LogInfoHelper m_Instance = null;
private static readonly object syncObj = new object();
#endregion #region Method
/// <summary>
/// 向日志文件中写入运行时信息
/// </summary>
/// <param name="message">要写入的运行时消息</param>
/// <param name="messageType"></param>
/// <returns></returns>
private bool WriteRunTimeMessage(IGetWriteLogInfo logInfo)
{
lock (m_Lock)
{
m_MessageQueue.Enqueue(logInfo);
}
return true;
} /// <summary>
/// 向日志文件中写入运行时的程序信息
/// </summary>
/// <param name="Message">要写入到日志文件中的信息</param>
/// <param name="messageType">要写入的日志类型</param>
/// <param name="isAutoAddTimeInfo">是否在写入的信息前加上当前系统时间</param>
/// <returns></returns>
public bool WriteRunTimeMessage(IGetWriteLogInfo logInfo, bool isAutoAddTimeInfo)
{
logInfo.Message = DateTime.Now.ToString() + "->" + logInfo.Message;
return WriteRunTimeMessage(logInfo);
}
/// <summary>
/// 异步写文件线程入口函数
/// </summary>
private void WriteTreadHandler()
{
Queue<IGetWriteLogInfo> tempQueue = new Queue<IGetWriteLogInfo>();
while (true)
{
StreamWriter sw = null;
#region 加锁拷贝部分
lock (m_MessageQueue)
{
int nowMessageCount = m_MessageQueue.Count;
for (int i = 0; i < nowMessageCount; i++)
{
try
{
tempQueue.Enqueue(m_MessageQueue.Dequeue());
}
catch (System.InvalidOperationException exp)
{
break;
}
}
}
#endregion
try
{
int nowTempQueueCount = tempQueue.Count;
for (int i = 0; i < nowTempQueueCount; i++)
{
IGetWriteLogInfo messageInfo = tempQueue.Dequeue();
long fileSize = 0; DateTime dtNow = DateTime.Now;
//日志文件名称
string FileName = messageInfo.BaseFileName + "-" + dtNow.ToShortDateString() + ".log";
//日志文件的完整路径
string FilePath = System.IO.Path.Combine(messageInfo.DictionaryPath, FileName);
FilePath = FilePath.Replace("/", "-");
//判断日志文件的大小
if (File.Exists(FilePath))
{
FileInfo FileInfo = new FileInfo(FilePath);
fileSize = FileInfo.Length / 1024 / 1024;
//当天异常日志大于10M的时候停止继续写入异常信息(PS:万一异常超级多 硬盘岂不是要炸~_~ 服务器上全天跑着鬼知道那儿有bug)
if (fileSize > 10)
{
continue;
}
}
sw = new StreamWriter(FilePath, true, Encoding.UTF8, 1024);
sw.AutoFlush = true;
sw.WriteLine(messageInfo.Message);
sw.Close();
//sw.WriteLine("------------------------------------------------------------");
}
}
catch (Exception exp)
{
throw exp;
}
finally
{
if (sw != null)
{
sw.Close();
sw.Dispose();
}
}
Thread.Sleep(1000);
}
}
#endregion #region Constructor
/// <summary>
/// 实例化对象的时候初始化写入线程
/// </summary>
private LogInfoHelper()
{
m_BackWriteThread = new Thread(WriteTreadHandler);
m_BackWriteThread.IsBackground = true;
m_BackWriteThread.Name = "异步写入日志文件线程";
m_BackWriteThread.Start();
}
#endregion
/// <summary>
/// 获取LogInfoHelper的实例
/// </summary>
public static LogInfoHelper GetInstance()
{
if (null == m_Instance)
{
lock (syncObj)
{
if (null == m_Instance)
{
m_Instance = new LogInfoHelper();
}
}
}
return m_Instance;
} } /// <summary>
/// 运行时需要写入到日志文件的信息类型
/// </summary>
public class LogMessageInfo : IGetWriteLogInfo
{ #region field
private string m_BaseName; private string m_MessageType; private string m_Message = string.Empty; private string m_DictionaryPath = string.Empty;
#endregion #region property
/// <summary>
/// 写入日志文件的基础文件名称
/// </summary>
public string BaseFileName
{
get { return m_BaseName; }
}
/// <summary>
/// 写入日志文件的日志类型
/// </summary>
public string MessageType
{
get { return m_MessageType; }
}
/// <summary>
/// 写入日志文件的日志信息
/// </summary>
public string Message
{
get { return m_Message; }
set { if (!string.IsNullOrEmpty(value)) { m_Message = value; } }
}
/// <summary>
/// 写入日志的文件存放目录
/// </summary>
public string DictionaryPath
{
get { return m_DictionaryPath; }
}
#endregion #region constructor
public LogMessageInfo(string DictionaryPath, string MessageFileBaseString, string MessageType, string Message)
{
if (!string.IsNullOrEmpty(DictionaryPath) && System.IO.Directory.Exists(DictionaryPath))
{
m_DictionaryPath = DictionaryPath;
}
else
{
throw new Exception("指定存放异常文件的目录不存在或者错误!!");
}
if (!string.IsNullOrEmpty(MessageFileBaseString) && !string.IsNullOrEmpty(MessageType))
{
m_BaseName = MessageFileBaseString;
m_MessageType = MessageType;
m_Message = Message;
}
}
#endregion /// <summary>
/// 获取要写入到日志文件的字符串数据
/// </summary>
/// <returns></returns>
public string GetLogString()
{
return m_Message;
}
} /// <summary>
/// 获取要写入到日志文件中的文字字符串
/// </summary>
public interface IGetWriteLogInfo
{
/// <summary>
/// 获取要写入到日志文件的字符串信息
/// </summary>
/// <returns></returns>
string GetLogString();
/// <summary>
/// 获取写入的日志文件的基名称
/// </summary>
string BaseFileName { get; }
/// <summary>
/// 获取写入的日志的日志类型
/// </summary>
string MessageType { get; }
/// <summary>
/// 获取要写入的日志的消息
/// </summary>
string Message { get; set; }
/// <summary>
/// 获取要写入日志文件的文件夹路径
/// </summary>
string DictionaryPath { get; }
}
}

  

LogInfoHelper的更多相关文章

  1. Pagination.js + Sqlite web系统分页

    前端使用 jquery pagination.js 插件. 环境准备:jquery.js.pagination.js.pagination.css 附件下载:https://files.cnblogs ...

随机推荐

  1. unittest框架学习笔记二之discover

    coding=utf-8'''Created on 2018/3/29 author:star Project:discover测试用例''' import unittest,time,oslist= ...

  2. C++之宏定义实现两个数最值

    转自:https://blog.csdn.net/baidu_33725271/article/details/69478782 方法一: 利用三重条件运算符 #include <stdio.h ...

  3. 用 Flask 来写个轻博客 (3) — (M)VC_连接 MySQL 和 SQLAlchemy

    目录 目录 前文列表 扩展阅读 前言 Models 模型 SQLAlchemy 安装 SQLAlchemy 安装 Mysql 建立 SQLAlchemy 和 Mysql 的连接 前文列表 用 Flas ...

  4. 2019杭电多校第三场hdu6609 Find the answer(线段树)

    Find the answer 题目传送门 解题思路 要想变0的个数最少,显然是优先把大的变成0.所以离散化,建立一颗权值线段树,维护区间和与区间元素数量,假设至少减去k才能满足条件,查询大于等于k的 ...

  5. 【NodeJS】Error: Cannot find module 'ms'

    报错原因: Error: Cannot find module 'ms' at Function.Module._resolveFilename (module.js::) at Function.M ...

  6. Chrome调试小技巧

    前言: 除了我们日常使用的调试方法,在Chrome中,其含有一些有意思的方法,有助于提高我们的开发调试效率. Sources页 command + p 文件跳转 使用Sublime的人或习惯用comm ...

  7. python中的模块以及包导入

    python中的导入关键字:import 以及from  import 1.import import一般用于导入包以及模块. 不过有个小问题: (1)当导入的是模块的时候是可以直接可以使用模块内的函 ...

  8. 长度为x的本质不同的串的出现次数 SPOJ - NSUBSTR 后缀自动机简单应用

    题意: 长度为x的本质不同的串的出现次数 题解: 先处理出每一个节点所对应的子串出现的次数 然后取max就好了 #include <set> #include <map> #i ...

  9. 自学Oracle心得

    基本术语: global name         全局数据库名 service name        服务名 SID                    实例名 常用命令: 1.       s ...

  10. python之常用的数据处理方法

    1.生成6位数验证码 "".join([random.choice(chars) for i in range(6)]) 2.密码加密 import hashlib def enc ...