zhaowc
2024-09-06 1b108e8d7335d5a5a59dfcf2f4eeef034a53b9b8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
 
namespace Utility.Tools
{
    public static class LogFile
    {
        /// <summary>写LOG到本地文件方法,message="存入信息",path="存储路径"</summary>
        public static void SaveLogToFile(string message, string path = "./log/defaultlog.txt")
        {
            FileInfo fi = null;
            StreamWriter logWriter = null;
            try
            {
                int fileLength = 1024 * 1024 * 5;//5MB
                fi = new FileInfo(path);
                if (!fi.Directory.Exists) { fi.Directory.Create(); }
                if (fi.Exists && fi.Length > fileLength)
                {
                    string newpath = path.Insert(path.LastIndexOf('.'), "_" + DateTime.Now.ToString("HHmmss"));
                    File.Move(path, newpath);
                }
                logWriter = new StreamWriter(path, true);
                logWriter.WriteLine(DateTime.Now.ToString() + ">>>" + message);
                logWriter.WriteLine("----->.");
            }
            catch (Exception ex)
            {
                //throw ex;
            }
            finally
            {
                fi = null;
                if (logWriter != null)
                {
                    logWriter.Close();
                    logWriter.Dispose();
                }
            }
        }
        //<summary>删除指定日期文件,保留7天</summary>
        public static void DeleteLogs(string Path, int days = 7)
        {
            //日志保留时长 单位:天
            
            if (days<7)
            {
                days = 7;
            }
 
            try
            {
                if (!Directory.Exists(Path))
                {
                    return;
                }
                var now = DateTime.Now;
                foreach (var f in Directory.GetFileSystemEntries(Path).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)
            {
 
            }
        }
    }
}