您的位置:首页 > 编程语言 > C#

c# 日志满2M自动新建日志文件

2018-01-29 10:59 281 查看
向系统记录日志时,遇到日志文件过大时,对于读取和写入都会耗费时间和内存;

考虑此情况,使用日志分多文件写入的方式日志文件满2M自动新建日志文件,原日志另命名存储日志。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/********************************************************************
** File Name: 日志类
** Author: Luc
** Create Time: 2018-01-18 15:20
** Modifier:
** Modify Time:
** Description: 记录日志信息
********************************************************************/
namespace test.BLL
{
public class WritLog
{
/// <summary>
/// 写日志信息(每满2M新建日志)luc:2017-1-17
/// </summary>
/// <param name="message">错误信息内容</param>
/// <param name="From">发生错误的来源(命名空间+类名+方法名),可为空</param>
public static void Writelog(string message)
{
string logpath = ConfigurationManager.AppSettings["LogPath"];
CommonLog(message, logpath);
}

/// <summary>
/// windows服务日志
/// </summary>
/// <param name="message">日志信息</param>
/// <param name="servername">服务名</param>
public static void WriteServerLog(string message, string servername)
{
string logpath = ConfigurationManager.AppSettings["LogServerath"];
string fullpath = GetPathStr(logpath, string.Format("{0}.log", servername));
CommonLog(message, fullpath);
}

public static void CommonLog(string message, string fullpath)
{
//文件所在路径
string logpath = Path.GetDirectoryName(fullpath);
//文件名称
string filename = Path.GetFileNameWithoutExtension(fullpath);

if (!Directory.Exists(logpath))
{
Directory.CreateDirectory(logpath);
}
if (!File.Exists(fullpath))
{
using (File.Create(fullpath)) { }
}
FileInfo fileinfo = new FileInfo(fullpath);
//获取指定目录下的所有的子文件
string[] files = Directory.GetFiles(logpath, filename + "*", SearchOption.TopDirectoryOnly);
if (fileinfo.Length > 2 * 1024 * 1024)
{
File.Move(fullpath, GetPathStr(logpath, string.Format("{0}.log", filename + "Old" + files.Length)));

if (!File.Exists(fullpath))
{
using (File.Create(fullpath)) { }
}
}
using (StreamWriter sw = File.AppendText(fullpath))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + "\t\n");
sw.WriteLine("-----------------------" + "\t\n");
sw.WriteLine("Message :" + message + "\t\n");
sw.WriteLine("====================================================================" + "\t\n\t\n\t\n");
sw.Close();
}
}

/// <summary>
/// 拼接地址串
/// </summary>
/// <param name="firstPath"></param>
/// <param name="secondPath"></param>
/// <returns></returns>
private static string GetPathStr(string firstPath, string secondPath)
{
StringBuilder builder = new StringBuilder();

builder.Append(firstPath);
builder.Append("\\");
builder.Append(secondPath);
return builder.ToString();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  日志
相关文章推荐