记录异常

时间:2013-01-30 10:59:33

标签: c# logging

我构建了一个对象来计算和记录错误。我在定时器结束后写日志。我不知道每个日志周期会发生多少错误,因此我将List _lastReadErrors设置为最多5个错误。在完整实现中,我想记录更多错误。日志记录对象应使用尽可能少的内存。如果我在列表中放入30个字符串,它会产生很大的不同吗?

public static class Monitor
{
    private static object _syncRoot = new object();

    private static DateTime _monitorStart;

    private static Timer _logTimer;

    private static int _readErrorsAbsolute;

    private static List<string> _lastReadErrors;

    public Monitor()
    {
        _monitorStart = DateTime.Now;
        _logTimer = new Timer();

        _readErrorsAbsolute = 0;

        _readErrors = new List<string>();

        _logTimer.Elapsed += writeLog;
        _logTimer.Interval = 3600000;
        _logTimer.AutoReset = true;
        _logTimer.Enabled = true;
    }

    public DateTime MonitorStart
    {
        get { return _monitorStart; }
    }

    public int ReadErrorsAbsolute
    {
        get { return _readErrorsAbsolute; }
    }

    public void ReadError(Exception ex)
    {
        Interlocked.Increment(ref _readErrorsAbsolute);

        lock (_syncRoot)
        {
            if (_lastReadErrors.Count > 4) _lastReadErrors.RemoveAt(0);
            _lastReadErrors.Add(ex.StackTrace);
        }
    }

    private void writeLog(Object sender, ElapsedEventArgs e)
    {
        string logString = buildLogString();

        // write the logstring into a memorystream

        _monitorStart = DateTime.Now;

        _readErrorsAbsolute = 0;

        lock (_syncRoot)
        {    
             _readErrors = new List<string>();
        }
    }

    private string buildLogString()
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("Date: " + _monitorStart.ToString() + " Errors: " + _readErrorsAbsolute.ToString() + Environment.NewLine);

        lock (_syncRoot)
        {
            foreach (string error in _lastReadErrors)
            {
                sb.Append(error + Environment.NewLine);
            }
        }

        return sb.ToString();
    }
}

0 个答案:

没有答案