Logs

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace ConsoleAppLogs
{
    /// <summary>
    /// 日志策略接口
    /// </summary>
    public interface ILogStrategy
    {
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="message">消息</param>
        void Write(string message);
    }

    /// <summary>
    /// 日志操作管理类
    /// </summary>
    public class Logs
    {
        private static ILogStrategy _ilogstrategy = new LogStrategy();//日志策略

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="message">消息</param>
        public static void Write(string message)
        {
            _ilogstrategy.Write(message);
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="ex">异常对象</param>
        public static void Write(Exception ex)
        {
            _ilogstrategy.Write(string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace));
        }
    }

    /// <summary>
    /// 基于txt文件的日志策略
    /// </summary>
    public class LogStrategy : ILogStrategy
    {
        private static object _locker = new object();//锁对象
        private static int _fileCountLimit = 31;//A long month of logs

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="message">消息</param>
        public void Write(string message)
        {
            lock (_locker)
            {
                FileStream fs = null;
                StreamWriter sw = null;
                try
                {
                    string basePath = AppDomain.CurrentDomain.BaseDirectory;
                    string logName = string.Format("log{0}.txt", DateTime.Now.ToString("yyyyMMdd"));
                    string fileName = Path.Combine(basePath, "logs", logName);

                    FileInfo fileInfo = new FileInfo(fileName);
                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }
                    if (!fileInfo.Exists)
                    {
                        fileInfo.Create().Close();
                        //清理文件,只保留一定数量的文件
                        FileInfo[] fis = fileInfo.Directory.GetFiles("log*.txt", SearchOption.TopDirectoryOnly);
                        if(fis.Length > _fileCountLimit)
                        {
                            Array.Sort(fis, delegate (FileInfo f1, FileInfo f2)
                            {
                                return f2.Name.CompareTo(f1.Name);
                            });
                            for(int i = _fileCountLimit; i < fis.Length; i++)
                            {
                                FileInfo f = fis[i];
                                f.Delete();
                            }
                        }
                    }
                    else if (fileInfo.Length > 2048 * 1000)
                    {
                        fileInfo.Delete();
                    }

                    fs = fileInfo.OpenWrite();
                    sw = new StreamWriter(fs);
                    sw.BaseStream.Seek(0, SeekOrigin.End);

                    sw.Write("{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    sw.Write(Environment.NewLine);

                    StackFrame stackFrame = FindStackFrame();
                    MethodBase methodBase = GetCallingMethodBase(stackFrame);
                    string callingClass = methodBase.ReflectedType.FullName;
                    string callingMethod = methodBase.Name;
                    sw.Write("{0}.{1}", callingClass, callingMethod);
                    sw.Write(Environment.NewLine);

                    sw.Write(message);
                    sw.Write(Environment.NewLine);
                    sw.Write(Environment.NewLine);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Flush();
                        sw.Close();
                    }
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
            }
        }

        private static StackFrame FindStackFrame()
        {
            StackTrace stackTrace = new StackTrace();
            int i = 0;
            foreach (StackFrame item in stackTrace.GetFrames())
            {
                MethodBase methodBase = item.GetMethod();
                string name = MethodBase.GetCurrentMethod().Name;
                if (!methodBase.Name.Equals("Write") && !methodBase.Name.Equals(name))
                    return new StackFrame(i, false);
                i++;
            }
            return null;
        }

        private static MethodBase GetCallingMethodBase(StackFrame stackFrame)
        {
            return stackFrame == null
                ? MethodBase.GetCurrentMethod() : stackFrame.GetMethod();
        }
    }
}