public async Task WritesLogEventWrapperModelToJson(LogLevel testLogLevel) { // Arrange var AddMessageAsyncWasCalled = false; var testLogEntryModel = new LogEntryModel { Details = "UnitTest" }; var expectedWrapperModel = new LogEventWrapperModel { ApplicationName = testApplicationName, LogLevel = testLogLevel, LogEntry = testLogEntryModel }; mockQueue.Setup(c => c.AddMessageAsync(It.IsAny <string>())) .Callback( (string message) => { var actualWrapper = JsonConvert.DeserializeObject <LogEventWrapperModel>(message); // Assert expectedWrapperModel.Compare(actualWrapper); AddMessageAsyncWasCalled = true; }) .Returns(Task.CompletedTask); // Act var logger = mockLogEventLoggerProvider.Object; await logger.WriteAsync(testLogLevel, testLogEntryModel); // Assert Assert.IsTrue(AddMessageAsyncWasCalled); }
public async Task WritesNullColumnsToJson() { // Arrange var AddMessageAsyncWasCalled = false; var testEntryModel = new LogEntryModel { WebPath = null }; mockQueue.Setup(c => c.AddMessageAsync(It.IsAny <string>())) .Callback( (string message) => { // Assert Assert.IsTrue(message.Contains("\"WebPath\":null"), "Expected null columns to be written to the queue"); AddMessageAsyncWasCalled = true; }) .Returns(Task.CompletedTask); // Act var logger = mockLogEventLoggerProvider.Object; await logger.WriteAsync(LogLevel.Information, testEntryModel); // Assert Assert.IsTrue(AddMessageAsyncWasCalled); }
/// <summary> /// Takes next <see cref="LogEntryModel"/> from the pipe. /// </summary> /// <returns>Next <see cref="LogEntryModel"/> in the pipe.</returns> public LogEntryModel Take() { LogEntryModel result = _nextEntry; _nextEntry = _parser.HasNext() ? _parser.GetEntry() : null; return(result); }
public async Task Post([FromBody] LogEntryModel model) { var log = _mapper.Map <LogEntry>(model); log.Id = 0; log.Date = DateTimeOffset.UtcNow; await _logService.AddLog(log, model.Key); }
public async Task WriteAsync(LogLevel logLevel, LogEntryModel logEntry) { var wrapper = new LogEventWrapperModel { ApplicationName = ApplicationName, LogLevel = logLevel, LogEntry = logEntry }; await queue.AddMessageAsync(wrapper); }
public static void AddException(Exception ex) { var entry = new LogEntryModel { Timestamp = DateTime.Now, UserName = "******", Content = ex.Message }; _instance.WriteEntry(entry); }
public static void AddEntry(string userName, string content) { var entry = new LogEntryModel { Timestamp = DateTime.Now, UserName = userName, Content = content, }; _instance.WriteEntry(entry); }
public async Task <PutItemResponse> SaveLogEntry(LogEntryModel logEntry) { // var logEntryId = Guid.NewGuid().ToString().ToLower(); var logEntryId = DateTimeOffset.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff"); logEntry.logEntryId = logEntryId; logEntry.entryDateTime = DateTimeOffset.Now.ToString("u"); logEntry.timestamp = Convert.ToInt32(Math.Floor(DateTimeOffset.Now.ToUnixTimeMilliseconds() / 1000.0)); return(await _dataHelper.PutItemAsync(_pk, $"LOG_ENTRY#{logEntryId}", logEntry)); }
public async Task <int> CreateLogEntry(LogEntryModel error) { _employeeContext.Errors.Add(new Logging { LoggingId = error.LoggingId, ErrorDateTime = error.ErrorDateTime, ErrorMessage = error.ErrorMessage, StackTrace = error.StackTrace }); return(await _employeeContext.SaveChangesAsync()); }
void WriteEntry(LogEntryModel entry) { var path = GetPathForDate(entry.Timestamp); var entries = GetExistingEntries(path); entries.Add(entry); lock (_writerLock) { File.WriteAllText(path, JsonConvert.SerializeObject(entries)); } }
public async Task <IActionResult> Post([FromBody] LogEntryModel logEntryModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var log = dataStructureConverter.Map <LogEntry, LogEntryModel>(logEntryModel); var result = await logService.Log(log); if (result.ResultCode == ResultCode.Success) { return(Created(string.Empty, log.Message)); } return(errorCodeConverter.Convert(result.ResultCode)); }
/// <summary> /// Gets the "one line" of log. /// </summary> /// <returns>Log entry.</returns> public LogEntryModel GetEntry() { LogEntryModel result = new LogEntryModel(DateTime.MinValue, new StringBuilder(_logName)); Match match = _regex.Match(_nextLine); if (CheckMatch(match, _nextLine)) { string value = match.Value; result = new LogEntryModel(ParseTimestamp(value), new StringBuilder(_nextLine)); result.Value.AppendLineIfNotNullOrEmpty(GetBlock()); } else { _nextLine = _stream.ReadLine(); } return(result); }
static void Main(string[] args) { CommandLineArguments arguments = new CommandLineArguments(args); if (!arguments.IsValid) { Console.ReadLine(); return; } IList <LogEntryModel> logEntries = new List <LogEntryModel>(); List <Pipe> pipes = new List <Pipe>(arguments.Inputs.Count); foreach (string inputPath in arguments.Inputs) { ILogParser parser = new DefaultLogParser(inputPath); pipes.Add(new Pipe(parser)); } pipes.ForEach(x => x.Take()); using (StreamWriter writer = new StreamWriter(arguments.OutputPath)) { while (pipes.Count > 0) { Pipe nextPipe = pipes .Aggregate((current, next) => DateTime.Compare(current.Peek().Timestamp, next.Peek().Timestamp) > 0 ? next : current); LogEntryModel logEntry = nextPipe.Take(); writer.WriteLine(logEntry.Value); if (nextPipe.IsDrained()) { pipes.Remove(nextPipe); } } } Console.WriteLine("Merge completed."); Console.ReadLine(); }
private bool PopulateCurrentEntry(LogEntryModel currentEntry, bool entryHasData, string lastKey, StringBuilder lastValueSb) { if (!String.IsNullOrEmpty(lastKey)) { switch (lastKey) { case "Timestamp": currentEntry.Timestamp = ParseTimeStamp(lastValueSb.ToString()); entryHasData = true; break; case "Message": currentEntry.Message = lastValueSb.ToString(); entryHasData = true; break; case "Category": currentEntry.Category = lastValueSb.ToString(); entryHasData = true; break; case "Priority": currentEntry.Priority = ParsePriority(lastValueSb.ToString()); entryHasData = true; break; case "EventId": currentEntry.EventId = lastValueSb.ToString(); entryHasData = true; break; case "Severity": currentEntry.Severity = lastValueSb.ToString(); entryHasData = true; break; case "Title": currentEntry.Title = lastValueSb.ToString(); break; } } return(entryHasData); }
public async void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { //Check logging for this level is enabled if (!IsEnabled(logLevel)) { return; } var entry = new LogEntryModel { Message = formatter(state, exception) }; if (exception != null) { entry.Message = Lists.ToDelimitedString(Environment.NewLine, null, exception.Message, entry.Message); entry.Stacktrace = string.IsNullOrWhiteSpace(exception.StackTrace) ? Environment.StackTrace : exception.StackTrace; var innerException = exception.GetInnermostException(); if (innerException != null) { entry.Stacktrace = Lists.ToDelimitedString(Environment.NewLine, null, innerException.StackTrace, entry.Stacktrace); entry.Details = Lists.ToDelimitedString( Environment.NewLine, null, innerException.Message, formatter(state, innerException)); } } if (!string.IsNullOrWhiteSpace(_category)) { entry.Source = _category; } await _provider.WriteAsync(logLevel, entry); }
public ActionResult EventDetails(int id, int?filter) { var system = (filter.HasValue && filter.Value >= 0 ? filter.Value.ToString(CultureInfo.InvariantCulture) : ""); try { var entry = DbContext.LogEntries.First(e => e.ID == id); var model = new LogEntryModel(entry, system) { IsAdmin = IsAdmin, PageTitle = "Event Details", SidebarMenu = BuildSidebarMenu("Admin", "Activity Log") }; return(View(model)); } catch (Exception) { return(RedirectToAction("ActivityLog", new { id = filter })); } }
public async void Post_PassesMessageToService() { // arrange var logService = new Mock <ILogService>(); logService.Setup(x => x.Log(It.IsAny <LogEntry>())) .ReturnsAsync(new Result <object>(ResultCode.Success)); IErrorCodeConverter processor = new ErrorCodeConverter(); var level = "warning"; var message = "test message"; var dataStructureConverterMoq = new Mock <IDataStructureConverter>(); dataStructureConverterMoq.Setup(x => x.Map <LogEntry, LogEntryModel>(It.IsAny <LogEntryModel>())) .Returns(new LogEntry() { Level = level, Message = message }); var sut = new LogController(logService.Object, processor, dataStructureConverterMoq.Object); var logEntryModel = new LogEntryModel() { Level = level, Message = message }; // act var result = await sut.Post(logEntryModel); var createdResult = result as CreatedResult; // assert logService.Verify(x => x.Log(It.Is <LogEntry>(entry => entry.Message == message))); }
public async void Post_WhenNotValid() { // arrange var logService = new Mock <ILogService>(); logService.Setup(x => x.Log(It.IsAny <LogEntry>())) .ReturnsAsync(new Result <object>(ResultCode.BadRequest)); IErrorCodeConverter processor = new ErrorCodeConverter(); var level = "warning"; var message = "test message"; var dataStructureConverterMoq = new Mock <IDataStructureConverter>(); dataStructureConverterMoq.Setup(x => x.Map <LogEntry, LogEntryModel>(It.IsAny <LogEntryModel>())) .Returns(new LogEntry() { Level = level, Message = message }); var sut = new LogController(logService.Object, processor, dataStructureConverterMoq.Object); var logEntryModel = new LogEntryModel() { Level = level, Message = message }; // act var result = await sut.Post(logEntryModel); var badRequestResult = result as BadRequestResult; // assert Assert.NotNull(badRequestResult); }
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest) { string message = JsonConvert.SerializeObject(logEntryModel, Formatting.Indented); Log.DebugFormat("Admin[{0}] {1}", isAdminRequest, message); }
/// <see cref="IWireMockLogger.DebugRequestResponse"/> public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest) { string message = JsonSerializer.Serialize(logEntryModel, options); _logger.LogDebug("Admin[{IsAdmin}] {Message}", isAdminRequest, message); }
public async Task <IEnumerable <LogEntryModel> > Parse(Stream s) { List <LogEntryModel> result = new List <LogEntryModel>(); LogEntryModel currentEntry = new LogEntryModel(); bool entryHasData = false; string lastKey = null; StringBuilder lastValueSb = null; try { using (StreamReader sr = new StreamReader(s)) { string line = await sr.ReadLineAsync(); while (line != null) { if (line == SEPARATOR) { if (entryHasData) { PopulateCurrentEntry(currentEntry, entryHasData, lastKey, lastValueSb); result = result.Union(Enumerable.Repeat(currentEntry, 1)).ToList(); entryHasData = false; currentEntry = new LogEntryModel(); lastKey = null; } } if (line.StartsWith(" ", StringComparison.Ordinal) || line.StartsWith("<", StringComparison.Ordinal)) { // Line continuation lastValueSb.AppendLine(line.TrimStart(' ')); } else { entryHasData = PopulateCurrentEntry(currentEntry, entryHasData, lastKey, lastValueSb); int colonIdx = line.IndexOf(':'); if (colonIdx >= 0) { // parse key-value lastKey = line.Substring(0, colonIdx); lastValueSb = new StringBuilder(); lastValueSb.AppendLine(line.Substring(colonIdx + 1).TrimStart(' ')); } } line = await sr.ReadLineAsync(); } } if (entryHasData) { result.Append(currentEntry); } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); throw; } return(result); }
private void ConvertLogEntriesToPumpingHistory() { List <HistoryModel> pumpingHistory = new List <HistoryModel>(); HistoryModel historyModel; DateTime sessionStartTimestamp = DateTime.MinValue; LogEntryModel sessionStart = null; long duration; // See if we had an existing session from the last logs if (Settings.SessionUptime != -1L) { if (Settings.SessionStart != string.Empty) { sessionStartTimestamp = DateTime.Parse(Settings.SessionStart).ToUniversalTime(); Settings.SessionStart = string.Empty; sessionStart = new LogEntryModel() { Timestamp = sessionStartTimestamp, Uptime = (uint)Settings.SessionUptime }; } Settings.SessionUptime = -1L; } // If we find a session start and a session end, save the pump history. Otherwise we will sync once the session is complete foreach (LogEntryModel logEntry in _connectedPump.Logs) { if (logEntry.Type == LogEntryType.PumpSessionStart) { if (sessionStart == null) { sessionStart = logEntry; sessionStartTimestamp = logEntry.Timestamp; } } else if (logEntry.Type == LogEntryType.PumpSessionEnd) { if (sessionStart != null) { duration = (long)logEntry.Uptime - (long)sessionStart.Uptime; // Sanity checking if ((duration > 0) && (sessionStart.Timestamp != DateTime.MinValue) && (logEntry.Timestamp != DateTime.MinValue) && (logEntry.Timestamp > sessionStart.Timestamp)) { historyModel = HistoryManager.Instance.CreateSession(SessionType.Pump); historyModel.StartTime = DateTime.SpecifyKind(sessionStart.Timestamp, DateTimeKind.Utc); historyModel.EndTime = DateTime.SpecifyKind(logEntry.Timestamp, DateTimeKind.Utc); historyModel.LeftBreastStartTime = historyModel.StartTime; historyModel.LeftBreastEndTime = historyModel.EndTime; historyModel.RightBreastStartTime = historyModel.StartTime; historyModel.RightBreastEndTime = historyModel.EndTime; historyModel.LeftBreastMilkVolume = logEntry.LeftVolume; historyModel.RightBreastMilkVolume = logEntry.RightVolume; historyModel.TotalMilkVolume = logEntry.LeftVolume + logEntry.RightVolume; historyModel.Storage = _storageType; pumpingHistory.Add(historyModel); } if (Settings.SessionStart != string.Empty) { Settings.SessionStart = string.Empty; } sessionStart = null; } } } if (sessionStart != null) { // If a pumping session is in progress, save the start time so we can recreate the full session // next time we pull the logs Settings.SessionStart = sessionStart.Timestamp.ToString("u"); Settings.SessionUptime = (long)sessionStart.Uptime; } // Wipe the existing logs _bluetoothManager.ClearLogs(); _connectedPump.PumpingSessions = pumpingHistory; }
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminrequest) { var message = JsonConvert.SerializeObject(logEntryModel, Formatting.Indented); _logger.LogDebug("Admin[{0}] {1}", isAdminrequest, message); }
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest) { // throw new NotImplementedException(); }
/// <see cref="IWireMockLogger.DebugRequestResponse"/> public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest) { // Log nothing }