Esempio n. 1
0
        public HttpLogShipper(LogBuffer logBuffer, SeqForwarderOutputConfig outputConfig)
        {
            if (logBuffer == null)
            {
                throw new ArgumentNullException(nameof(logBuffer));
            }
            if (outputConfig == null)
            {
                throw new ArgumentNullException(nameof(outputConfig));
            }

            if (string.IsNullOrWhiteSpace(outputConfig.ServerUrl))
            {
                throw new ArgumentException("The destination Seq server URL must be configured in SeqForwarder.json.");
            }

            _logBuffer          = logBuffer;
            _outputConfig       = outputConfig;
            _connectionSchedule = new ExponentialBackoffConnectionSchedule(QuietWaitPeriod);

            var baseUri = outputConfig.ServerUrl;

            if (!baseUri.EndsWith("/"))
            {
                baseUri += "/";
            }

            _httpClient = new HttpClient {
                BaseAddress = new Uri(baseUri)
            };
            _timer = new Timer(s => OnTick());
        }
Esempio n. 2
0
            public Logging.Log GetLog(LogBuffer logBuffer, bool withText)
            {
                var l = new Logging.Log {
                    level       = this.level,
                    time        = this.time,
                    runningTime = this.runningTime,
                };

                if (withText)
                {
                    if (strLen == 0)
                    {
                        l.text = "";
                    }
                    else
                    {
                        var str = new string('\0', strLen);

                        fixed(char *pStr = str)
                        Encoding.GetChars(logBuffer.buffer + bufOffset, bufLen, pStr, strLen);

                        l.text = str;
                    }
                }
#if DEBUG
                if (withText && l.text.GetHashCode() != hash)
                {
                    Console.CmdConsole.StdIO.Write("Log checksum failed!\n", Console.Color32.FromConsoleColor(ConsoleColor.Red));
                }
#endif
                return(l);
            }
Esempio n. 3
0
        public LogBuffer GetLogBuffer(string apiKey)
        {
            lock (_sync)
            {
                if (apiKey == null)
                {
                    if (_noApiKeyLogBuffer == null)
                    {
                        _log.Information("Creating a new default log buffer in {Path}", _bufferPath);
                        var buffer = new LogBuffer(_bufferPath, _bufferSizeBytes);
                        _noApiKeyLogBuffer = new ActiveLogBuffer(buffer, _shipperFactory.Create(buffer, _outputConfig.ApiKey));
                        _noApiKeyLogBuffer.Shipper.Start();
                    }
                    return(_noApiKeyLogBuffer.Buffer);
                }

                if (_buffersByApiKey.TryGetValue(apiKey, out var existing))
                {
                    return(existing.Buffer);
                }

                var subfolder = Path.Combine(_bufferPath, Guid.NewGuid().ToString("n"));
                _log.Information("Creating a new API key-specific log buffer in {Path}", subfolder);
                Directory.CreateDirectory(subfolder);
                File.WriteAllText(Path.Combine(subfolder, ".apikey"), MachineScopeDataProtection.Protect(apiKey));
                var newBuffer       = new LogBuffer(subfolder, _bufferSizeBytes);
                var newActiveBuffer = new ActiveLogBuffer(newBuffer, _shipperFactory.Create(newBuffer, apiKey));
                _buffersByApiKey.Add(apiKey, newActiveBuffer);
                newActiveBuffer.Shipper.Start();
                return(newBuffer);
            }
        }
Esempio n. 4
0
 /// <summary>
 /// Adds a new LogEntry to the LogBuffer.
 /// </summary>
 /// <param name="entry">The LogEntry to add</param>
 public void Log(LogEntry entry)
 {
     if (GlobalSettings.General.EnableBotLog || IsDebug)
     {
         LogBuffer.Add(entry);
     }
 }
Esempio n. 5
0
        // The odd three-stage initialization improves our chances of correctly tearing down the `LightningEnvironment`s within
        // `LogBuffer`s in the event of a failure during start-up. See: https://github.com/CoreyKaylor/Lightning.NET/blob/master/src/LightningDB/LightningEnvironment.cs#L252
        public void Load()
        {
            // At startup, we look for buffers and either delete them if they're empty, or load them
            // up if they're not. This garbage collection at start-up is a simplification,
            // we might try cleaning up in the background if the gains are worthwhile, although more synchronization
            // would be required.

            lock (_sync)
            {
                Directory.CreateDirectory(_bufferPath);

                var defaultDataFilePath = Path.Combine(_bufferPath, DataFileName);
                if (File.Exists(defaultDataFilePath))
                {
                    _log.Information("Loading the default log buffer in {Path}", _bufferPath);
                    var buffer = new LogBuffer(_bufferPath, _bufferSizeBytes);
                    if (buffer.Peek(0).Length == 0)
                    {
                        _log.Information("The default buffer is empty and will be removed until more data is received");
                        buffer.Dispose();
                        File.Delete(defaultDataFilePath);
                        var lockFilePath = Path.Combine(_bufferPath, LockFileName);
                        if (File.Exists(lockFilePath))
                        {
                            File.Delete(lockFilePath);
                        }
                    }
                    else
                    {
                        _noApiKeyLogBuffer = new ActiveLogBuffer(buffer, _shipperFactory.Create(buffer, _outputConfig.ApiKey));
                    }
                }

                foreach (var subfolder in Directory.GetDirectories(_bufferPath))
                {
                    var encodedApiKeyFilePath = Path.Combine(subfolder, ApiKeyFileName);
                    if (!File.Exists(encodedApiKeyFilePath))
                    {
                        _log.Information("Folder {Path} does not appear to be a log buffer; skipping", subfolder);
                        continue;
                    }

                    _log.Information("Loading an API-key specific buffer in {Path}", subfolder);
                    var apiKey = MachineScopeDataProtection.Unprotect(File.ReadAllText(encodedApiKeyFilePath));

                    var buffer = new LogBuffer(subfolder, _bufferSizeBytes);
                    if (buffer.Peek(0).Length == 0)
                    {
                        _log.Information("API key-specific buffer in {Path} is empty and will be removed until more data is received", subfolder);
                        buffer.Dispose();
                        Directory.Delete(subfolder, true);
                    }
                    else
                    {
                        var activeBuffer = new ActiveLogBuffer(buffer, _shipperFactory.Create(buffer, apiKey));
                        _buffersByApiKey.Add(apiKey, activeBuffer);
                    }
                }
            }
        }
Esempio n. 6
0
 /// <summary>
 /// Adds multiple new LogEntry objects to the LogBuffer.
 /// </summary>
 /// <param name="list">The list of log entries to add</param>
 public void LogRange(List <LogEntry> list)
 {
     if (GlobalSettings.General.EnableBotLog || IsDebug)
     {
         LogBuffer.AddRange(list);
     }
 }
Esempio n. 7
0
        /// <summary>
        /// 戦闘(分析)を開始する
        /// </summary>
        /// <param name="logLine">
        /// 対象のログ行</param>
        private void StartCombat(
            LogLineEventArgs logLine = null)
        {
            lock (this.CurrentCombatLogList)
            {
                if (!this.inCombat)
                {
                    if (!this.isImporting)
                    {
                        this.CurrentCombatLogList.Clear();
                        this.ActorHPRate.Clear();
                        this.partyNames = null;
                        this.combatants = null;
                        this.no         = 1;
                    }

                    Logger.Write("Start Combat");

                    // 自分の座標をダンプする
                    LogBuffer.DumpPosition(true);
                }

                this.inCombat = true;
            }

            this.StoreStartCombat(logLine);
        }
Esempio n. 8
0
        public void Enqueue(string source, string message, long time, long duration, int eventType)
        {
            Interlocked.Increment(ref _postedMessages);

            while (true)
            {
                LogBuffer buf = _last;

                if (!buf.PushMessage(source, message, time, duration, eventType))
                {
                    lock (lck)
                    {
                        if (!buf.Done)
                        {
                            continue;
                        }
                        LogBuffer nb = new LogBuffer();
                        if (Interlocked.CompareExchange(ref _last, nb, buf) == buf)
                        {
                            buf.Next = nb;
                        }
                    }
                }
                else
                {
                    break;
                }
            }
        }
Esempio n. 9
0
        private static async Task TasksWithScopedBuffer(int numTasksToStart, int parentTaskId)
        {
            using (LogBuffer.BeginScope(collapseOnTriggered: true))
            {
                var taskId = Interlocked.Increment(ref TaskCounter);
                try
                {
                    Log.Debug("Task {ParentTaskId}: Started the task {TaskId}", parentTaskId, taskId);

                    var failCounter = Interlocked.Decrement(ref FailCounter);

                    if (failCounter == 0)
                    {
                        // A single task will throw exception
                        Log.Debug("Task {TaskId} <-- was the one that failed", taskId);
                        throw new Exception("Failed");
                    }

                    if (failCounter < 0)
                    {
                        // Rest of the tasks end silently
                        return;
                    }

                    var tasks = Enumerable.Range(0, numTasksToStart)
                                .Select(
                        async x => {
                        await Task.Yield();         // yield first so we return the tasks before calling to make more
                        await TasksWithScopedBuffer(2, taskId);
                    }
                        );

                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Task {TaskId}: Exception thrown and caught", taskId);
                }
            }

            /* The output is (something like):
             * [Error] #5E4  Task 1501: Exception thrown and caught
             * [Debug] #2    Detailed trace of the task spawns (in order of occurrence):
             * [Debug] #3    Task 0: Started the task 1
             * [Debug] #4    Task 1: Started the task 2
             * [Debug] #6    Task 2: Started the task 4
             * [Debug] #B    Task 4: Started the task 9
             * [Debug] #14   Task 9: Started the task 18
             * [Debug] #1E   Task 18: Started the task 28
             * [Debug] #34   Task 28: Started the task 49
             * [Debug] #62   Task 49: Started the task 96
             * [Debug] #C0   Task 96: Started the task 189
             * [Debug] #17D  Task 189: Started the task 377
             * [Debug] #2F5  Task 377: Started the task 753
             * [Debug] #5E4  Task 753: Started the task 1501
             * [Debug] #5E4  Task 1501 <-- was the one that failed
             * [Infor] #2    Total tasks started and ended: 3001
             */
        }
Esempio n. 10
0
        public LogListerner(IDevice device, LogBuffer logBuffer)
        {
            _device    = device;
            _logBuffer = logBuffer;

            EntryDataOffset   = 0;
            EntryHeaderBuffer = new byte[ENTRY_HEADER_SIZE];
            EntryHeaderOffset = 0;
        }
Esempio n. 11
0
 static void Main(string[] args)
 {
     using (var logBuffer = new LogBuffer(4, 10, "test.log"))
     {
         logBuffer.Add("Test string 1");
         logBuffer.Add("Test string 2");
         logBuffer.Add("Test string 3");
     }
 }
Esempio n. 12
0
 public void ANewLogBufferIsEmpty()
 {
     using (var temp = TempFolder.ForCaller())
         using (var buffer = new LogBuffer(temp.AllocateFilename("mdb"), DefaultBufferSize))
         {
             var contents = buffer.Peek((int)DefaultBufferSize);
             Assert.Equal(0, contents.Length);
         }
 }
Esempio n. 13
0
 public HttpLogShipper(LogBuffer logBuffer, string apiKey, SeqForwarderOutputConfig outputConfig, ServerResponseProxy serverResponseProxy, HttpClient outputHttpClient)
 {
     _apiKey              = apiKey;
     _httpClient          = outputHttpClient ?? throw new ArgumentNullException(nameof(outputHttpClient));
     _logBuffer           = logBuffer ?? throw new ArgumentNullException(nameof(logBuffer));
     _outputConfig        = outputConfig ?? throw new ArgumentNullException(nameof(outputConfig));
     _serverResponseProxy = serverResponseProxy ?? throw new ArgumentNullException(nameof(serverResponseProxy));
     _connectionSchedule  = new ExponentialBackoffConnectionSchedule(QuietWaitPeriod);
     _timer = new Timer(s => OnTick());
 }
 /// <summary>
 ///     Logs the appropriate level of message.
 /// </summary>
 /// <param name="level">The level.</param>
 /// <param name="context">The context - if <see cref="Logger.UseContext" /> is false, this will be empty.</param>
 /// <param name="threadId">The thread identifier - if <see cref="Logger.UseThreadId"/> is false, this will be empty.</param>
 /// <param name="logTag">The log tag.</param>
 /// <param name="msg">The message.</param>
 public void LogThis(LoggingLevel level, string context, string threadId, LogTag logTag, string msg)
 {
     LogBuffer.Add(new LogEntry
     {
         Context  = context,
         LogTag   = logTag,
         Level    = level,
         Message  = msg,
         ThreadId = threadId
     });
 }
Esempio n. 15
0
 public void Log(string s, LogLevel level)
 {
     if ((int)Program.LogLevel >= (int)level)
     {
         LogBuffer.Add(s);
         if (LogBuffer.Count > Chip8Emu.DisplayRows)
         {
             LogBuffer.RemoveAt(0);
         }
     }
 }
Esempio n. 16
0
        private void TryWork()
        {
            // 自分のペットとの距離をダンプする
            LogBuffer.DumpMyPetDistance();

            // 定期的に自分の座標をダンプする
            if ((DateTime.Now - this.lastDumpPositionTimestamp).TotalSeconds >= 60.0)
            {
                this.lastDumpPositionTimestamp = DateTime.Now;
                LogBuffer.DumpPosition(true);
            }
        }
        internal void Trigger(bool isCollapsing = false)
        {
            if (CollapseOnTriggered)
            {
                ParentLogBufferScope?.Trigger(true);
            }

            if (isCollapsing)
            {
                LogBuffer.TriggerFlush(true);
            }
        }
Esempio n. 18
0
        private static void ConfigureGlobalLogger()
        {
            Serilog.Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information())
                                 .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
                                 .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal)
                                 .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning)
                                 .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName)
                                 .Enrich.WithProperty("InvocationId", InvocationId)
                                 .Enrich.WithProperty("ProcessId", ProcessId)
                                 .Enrich.FromLogContext()
                                 .WriteTo.Console(
                outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
                                 .WriteTo.Async(config =>
                                                config.File(
                                                    Path.Combine(AppDirectory, "logs", $"{AppName}-.log"),
                                                    outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
                                                    rollingInterval: RollingInterval.Day))
                                 .WriteTo.Conditional(
                e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki),
                config => config.GrafanaLoki(
                    OptionsAtStartup.Logger.Loki ?? string.Empty,
                    outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
                                 .WriteTo.Sink(new DelegatingSink(logEvent =>
            {
                try
                {
                    var message = logEvent.RenderMessage();

                    if (logEvent.Exception != null)
                    {
                        message = $"{message}: {logEvent.Exception}";
                    }

                    var record = new LogRecord()
                    {
                        Timestamp  = logEvent.Timestamp.LocalDateTime,
                        Context    = logEvent.Properties["SourceContext"].ToString().TrimStart('"').TrimEnd('"'),
                        SubContext = logEvent.Properties.ContainsKey("SubContext") ? logEvent.Properties["SubContext"].ToString().TrimStart('"').TrimEnd('"') : null,
                        Level      = logEvent.Level.ToString(),
                        Message    = message.TrimStart('"').TrimEnd('"'),
                    };

                    LogBuffer.Enqueue(record);
                    LogEmitted?.Invoke(null, record);
                }
                catch (Exception ex)
                {
                    Log.Information($"Misconfigured delegating logger: {ex.Message}");
                }
            }))
                                 .CreateLogger();
        }
Esempio n. 19
0
        /// <summary>
        /// ログを格納するスレッド
        /// </summary>
        private void StoreLogPoller()
        {
            if (this.logInfoQueue.IsEmpty)
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                return;
            }

            var preLog      = new string[3];
            var preLogIndex = 0;
            var ignores     = TimelineSettings.Instance.IgnoreLogTypes.Where(x => x.IsIgnore);

            var logs = new List <LogLineEventArgs>(this.logInfoQueue.Count);

            while (this.logInfoQueue.TryDequeue(out LogLineEventArgs log))
            {
                // 直前とまったく同じ行はカットする
                if (preLog[0] == log.logLine ||
                    preLog[1] == log.logLine ||
                    preLog[2] == log.logLine)
                {
                    continue;
                }

                preLog[preLogIndex++] = log.logLine;
                if (preLogIndex >= 3)
                {
                    preLogIndex = 0;
                }

                // 無効なログ?
                if (ignores.Any(x => log.logLine.Contains(x.Keyword)))
                {
                    continue;
                }

                logs.Add(log);
            }

            foreach (var log in logs)
            {
                // ダメージ系の不要なログか?
                if (LogBuffer.IsDamageLog(log.logLine))
                {
                    continue;
                }

                this.AnalyzeLogLine(log);
                Thread.Yield();
            }
        }
Esempio n. 20
0
    public LogService(bool logIntoFile, int oldLogsKeptDays, bool useMemBuf) // '-1' means keeping all logs without any erasing
    {
        RegisterCallback();

        _useMemBuf = useMemBuf;

        _memBuf = new LogBuffer(UserDefinedMemBufSize);

        if (logIntoFile)
        {
            try
            {
                DateTime dt = DateTime.Now;

                string logDir = LogUtil.CombinePaths(Application.persistentDataPath, "log", LogUtil.FormatDateAsFileNameString(dt));
                Directory.CreateDirectory(logDir);

                string logPath = Path.Combine(logDir, LogUtil.FormatDateAsFileNameString(dt) + '_' + LogUtil.FormatTimeAsFileNameString(dt) + ".txt");

                _logWriter           = new FileInfo(logPath).CreateText();
                _logWriter.AutoFlush = true;
                _logPath             = logPath;

                Log.Info("'Log Into File' enabled, file opened successfully. ('{0}')", _logPath);
                LastLogFile = _logPath;
            }
            catch (System.Exception ex)
            {
                Log.Info("'Log Into File' enabled but failed to open file.");
                Log.Exception(ex);
            }
        }
        else
        {
            Log.Info("'Log Into File' disabled.");
            LastLogFile = "";
        }

        if (oldLogsKeptDays > 0)
        {
            try
            {
                CleanupLogsOlderThan(oldLogsKeptDays);
            }
            catch (Exception e)
            {
                Log.Exception(e);
                Log.Error("Cleaning up logs ({0}) failed.", oldLogsKeptDays);
            }
        }
    }
Esempio n. 21
0
        public void PeekingDoesNotChangeState()
        {
            using (var temp = TempFolder.ForCaller())
                using (var buffer = new LogBuffer(temp.AllocateFilename("mdb"), DefaultBufferSize))
                {
                    buffer.Enqueue(new[] { Some.Bytes(140) });

                    var contents = buffer.Peek((int)DefaultBufferSize);
                    Assert.Equal(1, contents.Length);

                    var remainder = buffer.Peek((int)DefaultBufferSize);
                    Assert.Equal(1, remainder.Length);
                }
        }
Esempio n. 22
0
        public void AtLeastOneEventIsAlwaysDequeued()
        {
            using (var temp = TempFolder.ForCaller())
                using (var buffer = new LogBuffer(temp.AllocateFilename("mdb"), DefaultBufferSize))
                {
                    byte[] a1 = Some.Bytes(140), a2 = Some.Bytes(140), a3 = Some.Bytes(140);
                    buffer.Enqueue(new[] { a1, a2, a3 });

                    var contents = buffer.Peek(30);

                    Assert.Equal(1, contents.Length);
                    Assert.Equal(a1, contents[0].Value);
                }
        }
Esempio n. 23
0
 public LogComponent()
 {
     _logs    = new LogBuffer(100);
     _control = new TextBox
     {
         Dock       = DockStyle.Fill,
         Multiline  = true,
         Font       = new Font(FontFamily.GenericMonospace, 10),
         ScrollBars = ScrollBars.Both,
         WordWrap   = false,
         ReadOnly   = true
     };
     Oy.Subscribe <LogMessage>("Log", AppendLog);
 }
Esempio n. 24
0
        public void EntriesOverLimitArePurgedFifo()
        {
            using (var temp = TempFolder.ForCaller())
                using (var buffer = new LogBuffer(temp.AllocateFilename("mdb"), 4096))
                {
                    byte[] a1 = Some.Bytes(140), a2 = Some.Bytes(140), a3 = Some.Bytes(140);
                    buffer.Enqueue(new[] { a1, a2, a3 });

                    var contents = buffer.Peek((int)DefaultBufferSize);

                    Assert.Equal(2, contents.Length);
                    Assert.Equal(a2, contents[0].Value);
                    Assert.Equal(a3, contents[1].Value);
                }
        }
Esempio n. 25
0
        public void SizeHintLimitsDequeuedEventCount()
        {
            using (var temp = TempFolder.ForCaller())
                using (var buffer = new LogBuffer(temp.AllocateFilename("mdb"), DefaultBufferSize))
                {
                    byte[] a1 = Some.Bytes(140), a2 = Some.Bytes(140), a3 = Some.Bytes(140);
                    buffer.Enqueue(new[] { a1, a2, a3 });

                    var contents = buffer.Peek(300);

                    Assert.Equal(2, contents.Length);
                    Assert.Equal(a1, contents[0].Value);
                    Assert.Equal(a2, contents[1].Value);
                }
        }
Esempio n. 26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="logBuffer"></param>
        /// <param name="isClearBuffer">True : clear log buffer, False : unclear log buffer</param>
        public void Start(LogBuffer logBuffer, bool isClearBuffer)
        {
            if (!_isListener)
            {
                Action <IListener> startListener = null;
                l_listeners = new List <IListener>();
                L_Buffer    = logBuffer;
                if (L_Buffer.HasFlag(LogBuffer.Events))
                {
                    l_listeners.Add(new LogListerner(_device, LogBuffer.Events));
                }
                if (L_Buffer.HasFlag(LogBuffer.Main))
                {
                    l_listeners.Add(new LogListerner(_device, LogBuffer.Main));
                }
                if (L_Buffer.HasFlag(LogBuffer.Radio))
                {
                    l_listeners.Add(new LogListerner(_device, LogBuffer.Radio));
                }
                if (L_Buffer.HasFlag(LogBuffer.System))
                {
                    l_listeners.Add(new LogListerner(_device, LogBuffer.System));
                }
                if (startListener == null)
                {
                    startListener = delegate(IListener l)
                    {
                        l.LogDataReceivedEvent += this.OnLogDataReceived;
                        l.Start(isClearBuffer);
                    };
                }

                if (stopListener == null)
                {
                    stopListener = (l) => {
                        l.LogDataReceivedEvent -= this.OnLogDataReceived;
                        l.Stop(isClearBuffer);
                    };
                }

                Thread blockingT = new Thread(new ThreadStart(this.StartReceivedLogQueue));
                blockingT.Start();

                Parallel.ForEach <IListener>(l_listeners, startListener);

                _isListener = true;
            }
        }
Esempio n. 27
0
        protected override int Run(TextWriter cout)
        {
            try
            {
                var config = SeqForwarderConfig.Read(_storagePath.ConfigFilePath);
                var buffer = new LogBuffer(_storagePath.BufferPath, config.Storage.BufferSizeBytes);
                buffer.Truncate();
                return(0);
            }
            catch (Exception ex)
            {
                var logger = new LoggerConfiguration().WriteTo.LiterateConsole().CreateLogger();

                logger.Fatal(ex, "Could not truncate log buffer");
                return(1);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Log lỗi
        /// </summary>
        /// <param name="Error">Chi tiết lỗi cần log</param>
        protected void WriteError(string Error)
        {
            var match = Regex.Match(Error, "<MES>([^<]+)</MES>");

            if (match.Success)
            {
                Error     = match.Groups[1].Value;
                LastError = string.Format("\r\n*** [Lỗi] {0:HH:mm:ss} - {1} ***\r\n", DateTime.Now, Error);
            }
            else
            {
                LastError = string.Format("[Lỗi] {0:HH:mm:ss} - {1}", DateTime.Now, Error);
            }
            TotalError++;
            LogBuffer.Add(LastError);
            SetProcessState(ProcessState.Error);
        }
Esempio n. 29
0
        public void GivingTheLastSeenEventKeyRemovesPrecedingEvents()
        {
            using (var temp = TempFolder.ForCaller())
                using (var buffer = new LogBuffer(temp.AllocateFilename("mdb"), DefaultBufferSize))
                {
                    byte[] a1 = Some.Bytes(140), a2 = Some.Bytes(140), a3 = Some.Bytes(140);
                    buffer.Enqueue(new[] { a1, a2, a3 });

                    var contents = buffer.Peek(420);
                    Assert.Equal(3, contents.Length);

                    buffer.Dequeue(contents[2].Key);

                    var remaining = buffer.Peek(420);
                    Assert.Equal(0, remaining.Length);
                }
        }
Esempio n. 30
0
        public void EnumerationIsInOrder()
        {
            using (var temp = TempFolder.ForCaller())
                using (var buffer = new LogBuffer(temp.AllocateFilename("mdb"), DefaultBufferSize))
                {
                    byte[] a1 = Some.Bytes(140), a2 = Some.Bytes(140), a3 = Some.Bytes(140);
                    buffer.Enqueue(new[] { a1, a2, a3 });

                    var contents = new List <byte[]>();
                    buffer.Enumerate((k, v) =>
                    {
                        contents.Add(v);
                    });

                    Assert.Equal(3, contents.Count);
                    Assert.Equal(new[] { a1, a2, a3 }, contents);
                }
        }
Esempio n. 31
0
        /// <summary>
        /// Creates a socket that waits for traffic and sets up the handler modules
        /// </summary>
        /// <returns>Returns true if the listener starts successfully.  Otherwise, false.</returns>
		public bool Start()
		{
			HandlerSection handlers;

            // Get the handlers collection
			try
			{
				handlers = (HandlerSection)System.Configuration.ConfigurationManager.GetSection("handlerSection");
			}
			catch (Exception ex)
			{
				EventLogger.LogEvent("Could not load configuration because: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);

				return false;
			}

            // Ensure that a socket needs to be initialized.
            if (this.socket != null) { return true; }

            // Ensure that a socket needs to be initialized and bound.
            if (this.socket != null && this.socket.IsBound) { return true; }

			try
			{
				this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			}
			catch (Exception ex)
			{
				EventLogger.LogEvent("Could not create socket because: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);

				return false;
			}

            // Bind the socket to the specificed IP and port
			try
			{
				this.socket.Bind(new IPEndPoint(this.listenAddress, SYSLOG_PORT));
			}
			catch (Exception ex)
			{
				this.socket.Close();
				this.socket = null;

				EventLogger.LogEvent("Could not bind socket because: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);

				return false;
			}

            if (this.socket == null) { return false; }

            // Create a new LogBuffer that will be used to store messages until they are discarded or flushed to a persistent store.
			buffer = new LogBuffer(this.logBufferFlushFrequency);

			if (handlers != null)
			{
                // Load each module (handler) from the configuration file
				foreach (HandlerConfiguration handler in handlers.Handlers)
				{
					MessageHandler msgHandler = new MessageHandler(handler.AssemblyName, handler.ParserClassName,
								handler.StorageClassName, handler.ConnectionString);

                    // If the handler has a storage class then setup the buffer to temporarily store the messages
					if (handler.StorageClassName != null)
					{
						buffer.InitializeBuffer(msgHandler);
					}

                    // If the handler is configured for specific IP addresses, setup the IP handler lookup list
					if (handler.FilterIPAddresses != null)
					{
						string[] filters = handler.FilterIPAddresses.Split(',', ';');

						for (int i = 0; i < filters.Length; i++)
						{
							ipFilters.Add(filters[i], msgHandler);

                            // If the handler also has IP forwards set, add them to the IP Forwards lookup list
							if (handler.IPForwards != null && handler.IPForwards.Length > 0)
							{
								ipForwards.Add(filters[i], handler.IPForwards.Split(',', ';'));
							}
						}
					}
				}
			}

            // If any handler has an IP forward setup, create a send socket that will be used forward messages
			if (ipForwards.Count > 0)
			{
				try
				{
					sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
					sendSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
				}
				catch (Exception ex)
				{

				}
			}

			try
			{
                // Start the listen operation on the socket
				RegisterReceiveOperation();
			}
			catch (Exception ex)
			{
				EventLogger.LogEvent("Could not register socket on data received event because: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
				return false;
			}

			return true;
		}
Esempio n. 32
0
	/// <summary>
	/// Raises the log callback event.
	/// </summary>
	/// <param name="logString">Log string.</param>
	/// <param name="stackTrace">Stack trace.</param>
	/// <param name="type">Type.</param>
	protected void 	OnLogCallback(string logString, string stackTrace, LogType type)
	{
		if (type == LogType.Error || type == LogType.Exception)
		{
			LogBuffer buffer = new LogBuffer ();
			buffer.message 	= System.DateTime.Now.ToString () + ":" + logString.ToString () + "<<" + stackTrace + ">>";
			buffer.type 	= type;
			
			m_dBuffer.Add (buffer);
		}
	}