本文最后更新于 2024-05-07,文章可能存在过时内容,如有过时内容欢迎留言或者联系我进行反馈。

代码示例

/// <summary>
/// 插入日志公用方法
/// </summary>
/// <param name="msg"></param>
public static void insertLogs(string msg)
{
    //日志输出盘符物理路径
    string pf = ConfigurationManager.AppSettings["PF"];
    //判断文件路径是否存在,不存在则创建,记录日志
    DateTime dt = DateTime.Now;
    DeleteLogs(pf);
    string filetxt = pf + dt.ToString("yyyy-MM-dd") + ".log";
    if (!Directory.Exists(pf))//如果不存在就创建file文件夹                           
    {
        Directory.CreateDirectory(@"" + pf + "");//创建某盘下该文件夹  
    }
    StreamWriter fs = new StreamWriter(filetxt, true, System.Text.Encoding.UTF8);
    msg = msg + "\r\n";
    fs.Write(msg);
    fs.Flush();
    fs.Close();
}


//删除指定日期文件,保留7天
private static void DeleteLogs(string dir)
{
    int days = 7;
    //日志保留时长 单位:天
    string logsDay = ConfigurationManager.AppSettings["logsDay"];
    if (!string.IsNullOrEmpty(logsDay))
    {
        days = int.Parse(logsDay);
    }
    try
    {
        if (!Directory.Exists(dir))
        {
            return;
        }
        var now = DateTime.Now;
        foreach (var f in Directory.GetFileSystemEntries(dir).Where(f => File.Exists(f)))
        {
            var t = File.GetCreationTime(f);
            var elapsedTicks = now.Ticks - t.Ticks;
            var elaspsedSpan = new TimeSpan(elapsedTicks);
            if (elaspsedSpan.TotalDays > days)
            {
                File.Delete(f);
            }
        }
    }
    catch (Exception ex)
    {

    }
}