Create the file and read the file contents
Inheritance: MonoBehaviour
Exemplo n.º 1
0
        public void ckmon_files_and_text_files_are_produced()
        {
            var secret    = Guid.NewGuid().ToString();
            var binSecret = Encoding.UTF8.GetBytes(secret);

            TestHelper.Monitor.Info($"This will appear in ckmon, text files and the console: {secret}");
            GrandOutput.Default.Should().NotBeNull();
            GrandOutput.Default.Dispose();
            Directory.EnumerateFiles(TestHelper.LogFolder, "*.log", SearchOption.AllDirectories)
            .Select(f => File.ReadAllText(f))
            .Count(text => text.Contains(secret))
            .Should().Be(1);
            // ckmon files are now gzipped by default.
            int count = 0;

            foreach (var fName in Directory.EnumerateFiles(TestHelper.LogFolder, "*.ckmon", SearchOption.AllDirectories))
            {
                using (var input = LogReader.Open(fName))
                {
                    while (input.MoveNext())
                    {
                        if (input.Current.LogType != LogEntryType.CloseGroup &&
                            input.Current.Text.Contains(secret))
                        {
                            ++count;
                        }
                    }
                }
            }
            count.Should().Be(1);
            //
            TestHelper.WithWeakAssemblyResolver(() => TestHelper.Monitor.Info("From WeakAssemblyResolver."));
            TestHelper.Monitor.Info($"From WeakAssemblyResolver: {TestHelper.WithWeakAssemblyResolver( () => 3 )}");
        }
Exemplo n.º 2
0
        public void ShouldDiscardLogs()
        {
            LogReader     reader;
            Log           log;
            StringMatcher stringMatcher;
            StringMatcher discardMatcher;

            stringMatcher = new StringMatcher();
            stringMatcher.Add("Line");

            discardMatcher = new StringMatcher();
            discardMatcher.Add("Line 1");
            discardMatcher.Add("Line 3");
            discardMatcher.Add("Line 5");
            discardMatcher.Add("Line 7");
            discardMatcher.Add("Line 9");


            reader = new LogReader(new MockedLineReader(10), stringMatcher, discardMatcher);

            for (int t = 0; t < 5; t++)
            {
                log = reader.Read();
                Assert.AreEqual(t * 2, log.LineIndex);
                Assert.AreEqual($"Line {t*2}", log.ToSingleLine());
            }
            log = reader.Read();
            Assert.IsNull(log);
        }
Exemplo n.º 3
0
        public void ShouldReadAfterDiscardLogs()         // ex: used when a log file starts with comment
        {
            LogReader     reader;
            Log           log;
            StringMatcher stringMatcher;
            StringMatcher discardMatcher;

            stringMatcher = new StringMatcher();
            stringMatcher.Add("Line");

            discardMatcher = new StringMatcher();
            discardMatcher.Add("Line 0");
            discardMatcher.Add("Line 1");
            discardMatcher.Add("Line 2");
            discardMatcher.Add("Line 3");


            reader = new LogReader(new MockedLineReader(10), stringMatcher, discardMatcher);

            for (int t = 0; t < 6; t++)
            {
                log = reader.Read();
                Assert.AreEqual(t + 4, log.LineIndex);
                Assert.AreEqual($"Line {t+4}", log.ToSingleLine());
            }
            log = reader.Read();
            Assert.IsNull(log);
        }
Exemplo n.º 4
0
        public void SetUp()
        {
            mtaLogFilters = new GetMtaLogsRequest()
            {
                Actions = new[] { LogAction.Anticheat, LogAction.Api }
            };
            sourceAffectedModels = new List <SourceAffectedModel>();

            database              = new Mock <IDatabase>();
            filesManager          = new Mock <IReadOnlyFilesManager>();
            mapper                = new Mock <IMapper>();
            httpContextWriter     = new Mock <IHttpContextWriter>();
            logKeyWordsDictionary = new Mock <LogKeyWordsDictionary>();

            database.Setup(d => d.MtaLogRepository.GetMtaLogs(mtaLogFilters, It.IsNotNull <IList <string> >()))
            .ReturnsAsync(new List <MtaLog>()
            {
                new MtaLog(), new MtaLog()
            });
            database.Setup(d => d.PhoneSmsRepository.GetPhoneSms(mtaLogFilters, It.IsNotNull <IList <string> >()))
            .ReturnsAsync(new List <PhoneSms>()
            {
                new PhoneSms(), new PhoneSms()
            });
            mapper.Setup(m => m.Map <IEnumerable <MtaLogModel> >(It.IsNotNull <IEnumerable <MtaLog> >()))
            .Returns(new List <MtaLogModel>());
            mapper.Setup(m => m.Map <IEnumerable <MtaLogModel> >(It.IsNotNull <IEnumerable <PhoneSms> >()))
            .Returns(new List <MtaLogModel>());

            logReader = new LogReader(database.Object, filesManager.Object, mapper.Object, httpContextWriter.Object,
                                      logKeyWordsDictionary.Object);
        }
Exemplo n.º 5
0
        public Manager(HSReplayNetConfig config = null, IGameDataProvider gameDataProvider = null)
        {
            gameDataProvider = gameDataProvider ?? new HearthMirrorDataProvider();

            LogReader = new LogReader(new List <LogWatcherData>
            {
                LogWatcherConfigs.Power,
                LogWatcherConfigs.LoadingScreen,
                LogWatcherConfigs.Decks,
                LogWatcherConfigs.Arena,
                LogWatcherConfigs.Rachelle
            });

            Game = new Game(gameDataProvider);
            Game.HearthstoneExited += () => LogReader.Stop().Forget();

            _gameEventManager = new GameEventManager(Game, LogReader, gameDataProvider);

            _procWatcher          = new ProcessWatcher("Hearthstone");
            _procWatcher.OnStart += ProcessWatcher_OnStart;
            _procWatcher.OnExit  += ProcessWatcher_OnExit;

            LogConfigWatcher.Start();
            LogConfigUpdater.LogConfigUpdated      += Game.OnHearthstoneRestartRequired;
            LogConfigUpdater.LogConfigUpdateFailed += Game.OnLogConfigError;

            if (config != null)
            {
                HSReplayNet = new HSReplayNet(config);
                _hsReplayNetEventManager = new HSReplayNetEventManager(HSReplayNet, Game);
                HSReplayNet.UpdateAccount().Forget();
            }
        }
Exemplo n.º 6
0
        private void ConfigureServices(IConfigurationRoot configuration)
        {
            // Read MTGA log file.
            var logReader = new LogReader();

            var serviceCollection = new ServiceCollection();

            serviceCollection.Configure <ApplicationSettings>(settings =>
            {
                settings.Process = "MTGA";
                settings.SqliteConnectionString = "Data Source=crabtopus.db";
                settings.Endpoint = logReader.Endpoint;
                settings.Version  = logReader.Version;
            });

            serviceCollection.AddHttpClient("mtgarena", c => c.BaseAddress = logReader.AssetsUri);

            serviceCollection.AddTransient <OverlayViewModel>();
            serviceCollection.AddTransient <Overlay>();
            serviceCollection.AddTransient <ICardsService, CardsService>();
            serviceCollection.AddTransient <IFetchService, FetchService>();

            serviceCollection.AddSingleton <IBlobsService>(logReader);
            serviceCollection.AddSingleton <CardReader>();
            serviceCollection.AddSingleton <Database>();
            serviceCollection.AddSingleton <IConfiguration>(configuration);

            _serviceProvider = serviceCollection.BuildServiceProvider();
        }
Exemplo n.º 7
0
        private static void UpdateActionTree()
        {
            if (string.IsNullOrEmpty(_cmdLine.opponent))
            {
                Console.WriteLine("Opponent name is not set");
                return;
            }

            if (_oppActionTree == null)
            {
                CreateOppActionTree();
            }

            LogReader lr = new LogReader
            {
                Opponent   = _cmdLine.opponent,
                ActionTree = _oppActionTree
            };

            lr.ReadPath(_cmdLine.gameLogsPath, _cmdLine.includeLogs);

            if (_cmdLine.oppActionTreeFile != "")
            {
                SaveActionTree();
            }
        }
Exemplo n.º 8
0
        public void LevelDbSearchManifestTest()
        {
            DirectoryInfo directory = TestUtils.GetTestDirectory();

            var    currentStream    = File.OpenText(Path.Combine(directory.FullName, "CURRENT"));
            string manifestFilename = currentStream.ReadLine();

            currentStream.Close();

            Log.Debug($"Reading manifest from {manifestFilename}");

            // 08 01 02 00 00 01 00 00 00 00 00 00 00 00 00 00  ................

            ResultStatus result;

            using (Manifest manifest = new Manifest(directory))
            {
                using (var reader = new LogReader(new FileInfo(Path.Combine(directory.FullName, manifestFilename))))
                {
                    manifest.Load(reader);
                }
                result = manifest.Get(new byte[] { 0xf7, 0xff, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0x2f, 0x05, });
            }
            Assert.AreEqual(new byte[] { 0x08, 0x01, 0x02, 0x0, 0x0 }, result.Data.Slice(0, 5).ToArray());
        }
Exemplo n.º 9
0
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();

        _logReader = new LogReader(_logPath);

        btnShowDate.Active       = _logReader.ShowDate;
        btnShowCategory.Active   = _logReader.ShowCategory;
        btnShowIP.Active         = _logReader.ShowIP;
        btnShowPID.Active        = _logReader.ShowPID;
        btnShowWarnings.Active   = _logReader.ShowPHPWarnings;
        btnShowNotices.Active    = _logReader.ShowPHPNotices;
        btnShowStackTrace.Active = _logReader.ShowPHPStackTraces;

        textview.SizeAllocated += delegate { GoToEnd(); };

        _toggleEnabled = true;
        OnRefreshAction1Activated(this, null);

        Watcher = new FileSystemWatcher(System.IO.Path.GetDirectoryName(_logPath));
        Watcher.NotifyFilter        = NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.DirectoryName | NotifyFilters.FileName;
        Watcher.Changed            += new FileSystemEventHandler(OnConfigDirChange);
        Watcher.Deleted            += new FileSystemEventHandler(OnConfigDirChange);
        Watcher.Created            += new FileSystemEventHandler(OnConfigDirChange);
        Watcher.Renamed            += new RenamedEventHandler(OnConfigDirChange);
        Watcher.EnableRaisingEvents = true;
    }
Exemplo n.º 10
0
        public void CompressedReadWriteTests()
        {
            TestHelper.CleanupTestFolder();
            string          directoryPath = Path.Combine(TestHelper.TestFolder, "GzipCKMonWriterClientTest");
            ActivityMonitor m             = new ActivityMonitor();
            var             client        = new CKMonWriterClient(directoryPath, 20000, LogFilter.Undefined, true);

            m.Output.RegisterClient(client);
            using (m.OpenWarn().Send("Group test"))
            {
                m.Info().Send("Line test");
            }
            // This closes the client: the file is then compressed asynchronously
            // on a thread from the ThreadPool.
            Assert.That(client.IsOpened);
            m.Output.UnregisterClient(client);
            string    ckmonPath = TestHelper.WaitForCkmonFilesInDirectory(directoryPath, 1)[0];
            LogReader r         = LogReader.Open(ckmonPath);

            r.MoveNext();
            Assert.That(r.Current.LogType, Is.EqualTo(LogEntryType.OpenGroup));
            Assert.That(r.Current.Text, Is.EqualTo("Group test"));
            r.MoveNext();
            Assert.That(r.Current.LogType, Is.EqualTo(LogEntryType.Line));
            Assert.That(r.Current.Text, Is.EqualTo("Line test"));
            r.MoveNext();
            Assert.That(r.Current.LogType, Is.EqualTo(LogEntryType.CloseGroup));
            bool hasRemainingEntries = r.MoveNext();

            Assert.That(hasRemainingEntries, Is.False);
        }
Exemplo n.º 11
0
 public LogFlyoutViewModel()
     : base()
 {
     this.Logs = new ObservableCollection<Log>();
     this.LogReader = new LogReader(AppConfiguration.LogDatabase.ToSQLiteConnectionString());
     this.EventAggregator.GetEvent<LoadLogEvent>().Subscribe(e => Load());
 }
Exemplo n.º 12
0
        public void Will_Merge_Three_In_Order() // Also contains 2 logs with the same timestamp
        {
            var expected = LogReader.Read(OutputPath123);
            var result   = LogMerger.LogMerger.Merge(new string[] { InputPath1, InputPath2, InputPath3 });

            CollectionAssert.AreEqual(expected, result);
        }
Exemplo n.º 13
0
        public void Will_Merge_Two_In_Order()
        {
            var expected = LogReader.Read(OutputPath12);
            var result   = LogMerger.LogMerger.Merge(new string[] { InputPath1, InputPath2 });

            CollectionAssert.AreEqual(expected, result);
        }
Exemplo n.º 14
0
        public void Duplicate_Input()
        {
            var expected = LogReader.Read(InputPath1);
            var result   = LogMerger.LogMerger.Merge(new string[] { InputPath1, InputPath1 });

            CollectionAssert.AreEqual(expected, result);
        }
Exemplo n.º 15
0
 private DataTable TableFromSelected()
 {
     //get a DataTable from the currently selected ListBox log file
     return(LogReader.TableFromFile(
                $"{LogDir}\\{lstLogFiles.Items[lstLogFiles.SelectedIndex]}",
                false));
 }
Exemplo n.º 16
0
        private IronPythonConsole()
        {
            this.DataContext = this;
            this.InitializeComponent();

            this.scriptEngine              = Python.CreateEngine();
            this.stdout                    = new MemoryStream();
            this.writer                    = new LogWriter(this.console);
            this.stdin                     = new MemoryStream();
            this.reader                    = new LogReader(this.console);
            this.console.CommandEnter      = this.Execute;
            this.console.CommandBreak      = this.Abort;
            this.console.CommandSuggestion = this.Suggest;

            this.scriptEngine.Runtime.IO.SetOutput(this.stdout, this.writer);
            this.scriptEngine.Runtime.IO.SetInput(this.stdin, this.reader, Encoding.UTF8);
            this.scope = this.scriptEngine.CreateScope();

            this.scope.ImportModule("clr");
            this.scriptEngine.Execute("import clr", this.scope);
            this.scriptEngine.Execute("import System", this.scope);
            this.scriptEngine.Execute("clr.AddReference(\"System\")", this.scope);
            this.scriptEngine.Execute("clr.AddReference(\"System.Core\")", this.scope);
            this.scriptEngine.Execute("clr.AddReference(\"System.Linq\")", this.scope);
            this.scriptEngine.Execute("clr.ImportExtensions(System.Linq)", this.scope);
            this.scriptEngine.Execute("clr.AddReference(\"LogicCircuit\")", this.scope);
            this.scriptEngine.Execute("from LogicCircuit import *", this.scope);

            this.writer.WriteLine(this.scriptEngine.Setup.DisplayName);
            this.Prompt();
        }
Exemplo n.º 17
0
        static async Task Main(string[] args)
        {
            Console.WriteLine($"Starting up Leaf Log Reader...");

            LoadSettings(args);
            CheckDirectories();
            await CheckDatabase();

            var manager = new LogEntryTransferManager(settings);
            var reader  = new LogReader(settings, manager);

            if (!reader.FilesFound)
            {
                Console.WriteLine($"No files found to parse. Exiting...");
                return;
            }

            while (reader.Read())
            {
                await reader.Process();
            }

            Console.WriteLine($"Successfully copied {manager.CopiedCount} log entries from {reader.FileCount} file(s).");
            Console.WriteLine($"Exiting...");
        }
Exemplo n.º 18
0
 public LoggerJob(IHttpClientFactory httpClientFactory, LogReader reader)
 {
     _httpClientFactory = httpClientFactory;
     _reader            = reader;
     _source            = new CancellationTokenSource();
     _stoppingToken     = _source.Token;
 }
Exemplo n.º 19
0
        public void itShouldSupportMultipleAnalyzers()
        {
            var mockAnalyzer1 = new MockAnalyzer();
            var mockAnalyzer2 = new MockAnalyzer();

            var analyzers = new List <BaseLogAnalyzer>();

            analyzers.Add(mockAnalyzer1);
            analyzers.Add(mockAnalyzer2);

            var logReader = new LogReader(analyzers);

            var sb = new StringBuilder();

            sb.AppendLine("This is line 1");
            sb.AppendLine("This is line 2");
            sb.AppendLine("This is line 3");

            using (var stream = toStream(sb.ToString())) {
                logReader.ReadSource("source1", stream);
            }
            logReader.EndReadAll();

            Assert.AreEqual(3, mockAnalyzer1.LinesCount);
            Assert.AreEqual(3, mockAnalyzer1.LastLineNumberFromReader);

            Assert.AreEqual(3, mockAnalyzer2.LinesCount);
            Assert.AreEqual(3, mockAnalyzer2.LastLineNumberFromReader);
        }
Exemplo n.º 20
0
        private static void Main()
        {
            var timer = new Stopwatch();

            timer.Start();

            using (var logWriter = new LogWriter(PathToFile))
            {
                for (var i = 0; i < 10000; i++)
                {
                    logWriter.Log(i == 9999 ? $"Iteration number #{i} {DateTime.Now:F}" : $"Iteration number #{i}");
                }
            }

            using (var logReader = new LogReader(PathToFile))
            {
                logReader.ReadFile();
            }

            var executionTime = timer.ElapsedMilliseconds;

            timer.Stop();

            Console.WriteLine("Finished.");
            Console.WriteLine($"ExecutionTime: {executionTime} Milliseconds.");
            Console.Read();
        }
Exemplo n.º 21
0
        private void InitListener()
        {
            try
            {
                _serialPort = new SerialPort("COM3", BaudRate);
                _serialPort.Open();
                _serialPort.DiscardInBuffer();

                var serialReader = new AsyncSerialReader(_serialPort);

                FileStream logStream = new FileStream(LogFileName, FileMode.OpenOrCreate, FileAccess.Read);

                var logReader = new LogReader(null, logStream);

                _serialReader = new LoggedSerialReader(serialReader, logReader);

                //_serialReader = new FakeSerialReader(null);
                //_serialReader = new LogReader(null, _logStream);

                MainTimer.Start();
            }
            catch (IOException ex)
            {
                PrintMessage(ex.Message, true);
            }
        }
Exemplo n.º 22
0
        public async Task ReadEventLogTest()
        {
            // The data in this stream was read using a ShellStream, so the CRLF fixing
            // has already taken place.
            using (Stream stream = File.OpenRead(@"logcatevents.bin"))
            {
                LogReader reader = new LogReader(stream);
                var       entry  = await reader.ReadEntry(CancellationToken.None);

                Assert.IsInstanceOfType(entry, typeof(EventLogEntry));
                Assert.AreEqual(707, entry.ProcessId);
                Assert.AreEqual(1291, entry.ThreadId);
                Assert.AreEqual(2u, entry.Id);
                Assert.IsNotNull(entry.Data);
                Assert.AreEqual(39, entry.Data.Length);
                Assert.AreEqual(new DateTime(2015, 11, 16, 1, 48, 40, 525, DateTimeKind.Utc), entry.TimeStamp);

                var eventLog = (EventLogEntry)entry;
                Assert.AreEqual(0, eventLog.Tag);
                Assert.IsNotNull(eventLog.Values);
                Assert.AreEqual(1, eventLog.Values.Count);
                Assert.IsNotNull(eventLog.Values[0]);
                Assert.IsInstanceOfType(eventLog.Values[0], typeof(Collection <object>));

                var list = (Collection <object>)eventLog.Values[0];
                Assert.AreEqual(3, list.Count);
                Assert.AreEqual(0, list[0]);
                Assert.AreEqual(19512, list[1]);
                Assert.AreEqual("com.amazon.kindle", list[2]);

                entry = await reader.ReadEntry(CancellationToken.None);

                entry = await reader.ReadEntry(CancellationToken.None);
            }
        }
Exemplo n.º 23
0
        public ReplayPlayer(int currentPlayer, Board board, string log)
            : base(currentPlayer, board)
        {
            this.log = log;

            logReader = new LogReader(log, currentPlayer, board.Width, board.Height);;
        }
Exemplo n.º 24
0
        public void TestAlertEvents()
        {
            var textreader     = new StringReader(SampleLogString);
            var logreader      = new LogReader(textreader);
            var aggregator     = new LogAggregator(logreader, 1, 1000, 2000);
            var alertTriggered = false;
            var alertCancelled = false;

            aggregator.AlertTriggered += (sender, agg) => {
                //Console.WriteLine($"ALERT: LPS: {agg.RollingAverageLPS}, Total: {agg.RollingTotal}");
                alertTriggered = true;
                Assert.Equal(120, agg.RollingAverageLPS);
                Assert.Equal(240, agg.RollingTotal);
            };
            aggregator.AlertCancelled += (sender, agg) => {
                //Console.WriteLine($"CANCEL: LPS: {agg.RollingAverageLPS}, Total: {agg.RollingTotal}");
                alertCancelled = true;
                Assert.Equal(0, agg.RollingAverageLPS);
                Assert.Equal(0, agg.RollingTotal);
            };
            var cts = new System.Threading.CancellationTokenSource(3100);
            var t   = logreader.ReadFile(cts.Token);

            t.Wait(3100, cts.Token);
            Assert.True(alertTriggered);
            Assert.True(alertCancelled);
        }
Exemplo n.º 25
0
        public async Task ReadLogTests()
        {
            using (Stream stream = File.OpenRead(@"logcat.bin"))
                using (ShellStream shellStream = new ShellStream(stream, false))
                {
                    LogReader reader = new LogReader(shellStream);

                    // This stream contains 3 log entries. Read & validate the first one,
                    // read the next two ones (to be sure all data is read correctly).
                    var log = await reader.ReadEntry(CancellationToken.None);

                    Assert.IsInstanceOfType(log, typeof(AndroidLogEntry));

                    Assert.AreEqual(707, log.ProcessId);
                    Assert.AreEqual(1254, log.ThreadId);
                    Assert.AreEqual(3u, log.Id);
                    Assert.IsNotNull(log.Data);
                    Assert.AreEqual(179, log.Data.Length);
                    Assert.AreEqual(new DateTime(2015, 11, 14, 23, 38, 20, 590, DateTimeKind.Utc), log.TimeStamp);

                    var androidLog = (AndroidLogEntry)log;
                    Assert.AreEqual(4, androidLog.Priority);
                    Assert.AreEqual("ActivityManager", androidLog.Tag);
                    Assert.AreEqual("Start proc com.google.android.gm for broadcast com.google.android.gm/.widget.GmailWidgetProvider: pid=7026 uid=10066 gids={50066, 9997, 3003, 1028, 1015} abi=x86", androidLog.Message);

                    Assert.IsNotNull(await reader.ReadEntry(CancellationToken.None));
                    Assert.IsNotNull(await reader.ReadEntry(CancellationToken.None));
                }
        }
Exemplo n.º 26
0
    void Start()
    {
        reader    = GetComponent <LogReader>();
        writer    = GetComponent <AnalysisWriter>();
        calulator = GetComponent <Calculator>();
        rae       = GetComponent <ReplayAnalysisEngine>();
        extender  = GetComponent <ReplayExtender>();

        gameWidth  = float.IsNaN(gameWidth) ?  Screen.height * Camera.mainCamera.aspect : gameWidth;
        originX    = (Screen.width - gameWidth) / 2f;
        gameHeight = float.IsNaN(gameHeight) ? Screen.height : gameHeight;

        overalOptionsRect = new Rect(originX, 0, gameWidth, gameHeight);
        optionsLabelRect  = new Rect(overalOptionsRect.x + overalOptionsRect.width / 2 - standardButtonWidth / 2,
                                     overalOptionsRect.y + borderSpacing,
                                     standardButtonWidth,
                                     standardButtonHeight);
        optionToolbarRect = new Rect(originX + borderSpacing,
                                     optionsLabelRect.yMax + borderSpacing,
                                     overalOptionsRect.width - 2 * borderSpacing,
                                     standardButtonHeight);

        mainOptionsRect = new Rect(overalOptionsRect.x + borderSpacing,
                                   optionToolbarRect.yMax + borderSpacing,
                                   overalOptionsRect.width - 2 * borderSpacing,
                                   overalOptionsRect.yMax - optionToolbarRect.yMax - 2 * borderSpacing - standardButtonHeight);

        optionNames.Add("Replay Options");
        optionNames.Add(reader.GUIName);
        optionNames.Add(writer.GUIName);
        optionNames.Add(calulator.GUIName);
        optionNames.Add(extender.GUIName);
    }
Exemplo n.º 27
0
        public bool ProcessLogs()
        {
            LogConsumer.OnProgress -= LogConsumer_OnProgress;
            LogConsumer.OnProgress += LogConsumer_OnProgress;

            bool done = false;
            var  logs = LogSource.GetLogSources();

            if (logs.Length == 0)
            {
                OnLogsProcessingProgress(this.GetType().Name, "No logs to process since no LogSources were retrieved.", LogLevel.Verbose);
            }
            for (int k = 0; k < logs.Length; k++)
            {
                LogReader.Open(logs[k]);
                OnLogsProcessingProgress(this.GetType().Name, string.Format("Started processing log source {0} ({1}/{2}).", LogReader.SourceName, k + 1, logs.Length), LogLevel.Verbose);
                while (!done && LogReader.HasMoreLines)
                {
                    string line = LogReader.ReadLine();
                    done = LogConsumer.ConsumeLogEntry(line, LogReader.LineNumber, LogReader.SourceName);
                }
                LogReader.Close();
                if (done)
                {
                    OnLogsProcessingProgress(this.GetType().Name, string.Format("LogConsumer is DONE. Terminated processing in log source {0} ({1}/{2}).", logs[k], k + 1, logs.Length), LogLevel.Verbose);
                    break;
                }
                else
                {
                    OnLogsProcessingProgress(this.GetType().Name, string.Format("LogConsumer is NOT DONE after processing log source {0} ({1}/{2}).", logs[k], k + 1, logs.Length), LogLevel.Verbose);
                }
            }
            return(done);
        }
Exemplo n.º 28
0
        public void Reader_Works()
        {
            var expected = Input1Logs;
            var result   = LogReader.Read(InputPath1);

            CollectionAssert.AreEqual(expected, result);
        }
        public void BinaryGzip_reconfiguration()
        {
            string folder = TestHelper.PrepareLogFolder(nameof(BinaryGzip_reconfiguration));
            var    h      = new Handlers.BinaryFileConfiguration()
            {
                Path = folder + @"\FirstPath",
                UseGzipCompression = false
            };
            var c = new GrandOutputConfiguration().AddHandler(h);

            var m = new ActivityMonitor(applyAutoConfigurations: false);

            using (GrandOutput g = new GrandOutput(c))
            {
                g.EnsureGrandOutputClient(m);

                m.Trace("No Compression.");
                // We must ensure that the log above will use the current configuration.
                // This is by design and is a good thing: there is no causality/ordering between log emission and sink reconfigurations.
                Thread.Sleep(100);

                h.UseGzipCompression = true;
                g.ApplyConfiguration(c, true);
                m.Trace("With Compression.");
                Thread.Sleep(100);

                h.Path = folder + @"\SecondPath";
                g.ApplyConfiguration(c, true);
                m.Trace("With Compression (in second folder).");
                Thread.Sleep(100);

                h.UseGzipCompression = false;
                g.ApplyConfiguration(c, true);
                m.Trace("No Compression (in second folder).");
            }
            // First file is NOT compressed, the second one is.
            var fileNamesFirst = Directory.EnumerateFiles(folder + @"\FirstPath").ToList();

            fileNamesFirst.Should().BeInAscendingOrder().And.HaveCount(2).And.NotContain(s => s.EndsWith(".tmp"), "Temporary files have been closed.");
            File.ReadAllText(fileNamesFirst[0]).Should().Contain("No Compression.");
            File.ReadAllText(fileNamesFirst[1]).Should().NotContain("With Compression.", "Cannot read it in clear text since it is compressed...");
            using (var reader = LogReader.Open(fileNamesFirst[1]))
            {
                reader.MoveNext().Should().BeTrue();
                reader.Current.Text.Should().Be("With Compression.");
            }
            // First file is compressed, not the second one.
            var fileNamesSecond = Directory.EnumerateFiles(folder + @"\SecondPath").ToList();

            fileNamesSecond.Should().BeInAscendingOrder().And.HaveCount(2).And.NotContain(s => s.EndsWith(".tmp"), "Temporary files have been closed.");
            File.ReadAllText(fileNamesSecond[0]).Should().NotContain("With Compression (in second folder).", "The fist file is compressed...");
            // We restrict the log entries to the one of our monitor: this filters out the logs from the DispatcherSink.
            using (var reader = LogReader.Open(fileNamesSecond[0], filter: new LogReader.MulticastFilter(m)))
            {
                reader.MoveNext().Should().BeTrue();
                reader.Current.Text.Should().Be("With Compression (in second folder).");
            }
            File.ReadAllText(fileNamesSecond[1]).Should().Contain("No Compression (in second folder).");
        }
Exemplo n.º 30
0
 private void LogReader_OnReadProgress(LogReader reader, ReadProgressEventArgs args)
 {
     if (args.LineNumber % _logInterval == 0)
     {
         setText(filterTextBox, $"Analyzing line {args.LineNumber} of {args.SourceName} ...{Environment.NewLine}");
         adjustLogIntervalIfNeeded();
     }
 }
Exemplo n.º 31
0
        public void ReadTest1()
        {
            var log    = "";
            var reader = new LogReader(Helper.CreateStreamReader(log));
            var line   = reader.Read();

            Assert.Null(line);
        }
Exemplo n.º 32
0
        public void ReadTest5()
        {
            var log    = "2010-04-25 09:49:31 GET /index.asp 183.64.134";
            var reader = new LogReader(Helper.CreateStreamReader(log));
            var line   = reader.Read();

            Assert.Null(line);
        }
Exemplo n.º 33
0
        public MainWindow()
        {
            InitializeComponent();

            _Reader = new LogReader("General");
            Log.AddReader(_Reader);
            textBox.DataContext = _Reader;

            AddPage(new MainPage());
            AddPage(new ScriptsPage());
        }
Exemplo n.º 34
0
        public void LogEntryReadWrite()
        {
            var exInner = new CKExceptionData( "message", "typeof(exception)", "assemblyQualifiedName", "stackTrace", null, "fileName", "fusionLog", null, null );
            var ex2 = new CKExceptionData( "message2", "typeof(exception2)", "assemblyQualifiedName2", "stackTrace2", exInner, "fileName2", "fusionLog2", null, null );
            var exL = new CKExceptionData( "loader-message", "typeof(loader-exception)", "loader-assemblyQualifiedName", "loader-stackTrace", null, "loader-fileName", "loader-fusionLog", null, null );
            var exAgg = new CKExceptionData( "agg-message", "typeof(agg-exception)", "agg-assemblyQualifiedName", "agg-stackTrace", ex2, "fileName", "fusionLog", null, new[]{ ex2, exL } );

            var prevLog = DateTimeStamp.UtcNow;
            ILogEntry e1 = LogEntry.CreateLog( "Text1", new DateTimeStamp( DateTime.UtcNow, 42 ), LogLevel.Info, "c:\\test.cs", 3712, ActivityMonitor.Tags.CreateDependentActivity, exAgg );
            ILogEntry e2 = LogEntry.CreateMulticastLog( Guid.Empty, LogEntryType.Line, prevLog, 5, "Text2", DateTimeStamp.UtcNow, LogLevel.Fatal, null, 3712, ActivityMonitor.Tags.CreateDependentActivity, exAgg );

            using( var mem = new MemoryStream() )
            using( var w = new CKBinaryWriter( mem ) )
            {
                w.Write( LogReader.CurrentStreamVersion );
                e1.WriteLogEntry( w );
                e2.WriteLogEntry( w );
                w.Write( (byte)0 );
                w.Flush();

                byte[] versionBytes = new byte[4];
                mem.Position = 0;
                mem.Read( versionBytes, 0, 4 );
                Assert.That( BitConverter.ToInt32( versionBytes, 0 ), Is.EqualTo( LogReader.CurrentStreamVersion ) );

                using( var reader = new LogReader( mem, LogReader.CurrentStreamVersion, 4 ) )
                {
                    Assert.That( reader.MoveNext() );
                    Assert.That( reader.Current.Text, Is.EqualTo( e1.Text ) );
                    Assert.That( reader.Current.LogLevel, Is.EqualTo( e1.LogLevel ) );
                    Assert.That( reader.Current.LogTime, Is.EqualTo( e1.LogTime ) );
                    Assert.That( reader.Current.FileName, Is.EqualTo( e1.FileName ) );
                    Assert.That( reader.Current.LineNumber, Is.EqualTo( e1.LineNumber ) );
                    Assert.That( reader.Current.Exception.ExceptionTypeAssemblyQualifiedName, Is.EqualTo( e1.Exception.ExceptionTypeAssemblyQualifiedName ) );
                    Assert.That( reader.Current.Exception.ToString(), Is.EqualTo( e1.Exception.ToString() ) );

                    Assert.That( reader.MoveNext() );
                    Assert.That( reader.CurrentMulticast.PreviousEntryType, Is.EqualTo( LogEntryType.Line ) );
                    Assert.That( reader.CurrentMulticast.PreviousLogTime, Is.EqualTo( prevLog ) );
                    Assert.That( reader.Current.Text, Is.EqualTo( e2.Text ) );
                    Assert.That( reader.Current.LogTime, Is.EqualTo( e2.LogTime ) );
                    Assert.That( reader.Current.FileName, Is.Null );
                    Assert.That( reader.Current.LineNumber, Is.EqualTo( 0 ), "Since no file name is set, line number is 0." );
                    Assert.That( reader.Current.Exception.ExceptionTypeAssemblyQualifiedName, Is.EqualTo( e2.Exception.ExceptionTypeAssemblyQualifiedName ) );
                    Assert.That( reader.Current.Exception.ToString(), Is.EqualTo( e2.Exception.ToString() ) );
                    
                    Assert.That( reader.MoveNext(), Is.False );
                    Assert.That( reader.BadEndOfFileMarker, Is.False );
                }
            }

        }
Exemplo n.º 35
0
    void Start()
    {
        reader = GetComponent<LogReader>();
        writer = GetComponent<AnalysisWriter>();
        calulator = GetComponent<Calculator>();
        rae = GetComponent<ReplayAnalysisEngine>();
        extender = GetComponent<ReplayExtender>();

        gameWidth = float.IsNaN(gameWidth) ?  Screen.height * Camera.mainCamera.aspect : gameWidth;
        originX = (Screen.width - gameWidth) / 2f;
        gameHeight = float.IsNaN(gameHeight) ? Screen.height : gameHeight;

        overalOptionsRect = new Rect(originX, 0, gameWidth, gameHeight);
        optionsLabelRect = new Rect(overalOptionsRect.x + overalOptionsRect.width / 2 - standardButtonWidth / 2,
            overalOptionsRect.y + borderSpacing,
            standardButtonWidth,
            standardButtonHeight);
        optionToolbarRect = new Rect(originX + borderSpacing,
            optionsLabelRect.yMax + borderSpacing,
            overalOptionsRect.width - 2 * borderSpacing,
            standardButtonHeight);

        mainOptionsRect = new Rect(overalOptionsRect.x + borderSpacing,
            optionToolbarRect.yMax + borderSpacing,
            overalOptionsRect.width - 2 * borderSpacing,
            overalOptionsRect.yMax - optionToolbarRect.yMax - 2 * borderSpacing - standardButtonHeight);

        optionNames.Add("Replay Options");
        optionNames.Add(reader.GUIName);
        optionNames.Add(writer.GUIName);
        optionNames.Add(calulator.GUIName);
        optionNames.Add(extender.GUIName);
    }
    // Use this for initialization
    void Start()
    {
        dictionary = GetComponent<PrefabDictionary>();

        reader = GetComponent<LogReader>();
        if(reader == null)
            Debug.LogError("No LogReader attached to the Replay Analysis Engine.");

        calculator = GetComponent<Calculator>();
        if (calculator == null)
            Debug.LogError("No Calculator attached to the Replay Analysis Engine.");

        writer = GetComponent<AnalysisWriter>();
        if (writer == null)
            Debug.LogError("No LogWriter attached to the Replay Analysis Engine.");

        extender = GetComponent<ReplayExtender>();
        if (extender == null)
            Debug.LogWarning("No ReplayExtender attached to the Replay Analysis Engine. Adding a DummyExtender.");
        this.gameObject.AddComponent<ReplayExtender>();

        foreach (GameObject go in (FindObjectsOfType(typeof(GameObject)) as GameObject[])) {
            if (go != this.gameObject && go.GetComponent<ReplayBehavior>() == null) {
                ReplayBehavior rb = go.AddComponent<ReplayBehavior>();
                rb.ReplayTag = ReplayBehavior.RAETag.Given;
                rb.RecordTouching = false;
            }
        }
    }