1

我建立了一个对象来计算和记录错误。我在计时器过去后写日志。我不知道每个日志周期会发生多少错误,所以我将 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();
    }
}
4

0 回答 0