Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion OpenFreq.Client/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public static void Main(string[] args)
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", "OpenFreqClient")
.Enrich.With(new ElapsedEnricher())
.Enrich.With(new UtcTimestampEnricher())
.WriteTo.SessionFile(logFile)
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss.fff} {Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
Expand All @@ -65,6 +66,7 @@ public static void Main(string[] args)
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", "OpenFreqClient")
.Enrich.With(new ElapsedEnricher())
.Enrich.With(new UtcTimestampEnricher())
.WriteTo.SessionFile(logFile)
.CreateLogger();
#endif
Expand All @@ -78,7 +80,7 @@ public static void Main(string[] args)
Version = Assembly.GetExecutingAssembly()
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
?.InformationalVersion ?? "unknown";
Log.Information("OpenFreq Client {Version} starting at {WallTime:o}", Version, DateTimeOffset.Now);
Log.Information("OpenFreq Client {Version}", Version);
SessionLog.DeleteOld(logsDirectory, TimeSpan.FromDays(30));

// Set up dependency injection
Expand Down
5 changes: 3 additions & 2 deletions OpenFreq.Common.Tests/SessionLogTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public void SessionFile_WritesInvariantNumbersInAnyCulture()

using var logger = new LoggerConfiguration()
.Enrich.With(new ElapsedEnricher())
.Enrich.With(new UtcTimestampEnricher())
.WriteTo.SessionFile(path)
.CreateLogger();
logger.Information("PTT start: Bob ({PeerId}) on {FreqMhz:F3} MHz", "id", 139.7);
Expand All @@ -64,8 +65,8 @@ public void SessionFile_WritesInvariantNumbersInAnyCulture()
CultureInfo.CurrentCulture = culture;
}

// Without the enricher, Serilog writes "{Elapsed:F3}" as text.
Assert.Matches(@"^\d+\.\d{3} \[INF\] \[\] PTT start: Bob \(id\) on 139\.700 MHz\r?\n$", File.ReadAllText(path));
// Without the enrichers, Serilog writes "{UtcTimestamp:...}" or "{Elapsed:F3}" as text.
Assert.Matches(@"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z \(\d+\.\d{3}\) \[INF\] \[\] PTT start: Bob \(id\) on 139\.700 MHz\r?\n$", File.ReadAllText(path));
}

private string CreateFile(string name, DateTime lastWriteUtc)
Expand Down
23 changes: 17 additions & 6 deletions OpenFreq.Common/Logging/SessionLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,27 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
new ScalarValue(Stopwatch.GetElapsedTime(_start).TotalSeconds)));
}

/// <summary>
/// Adds <c>UtcTimestamp</c>, the current UTC timestamp to each log event.
/// </summary>
public sealed class UtcTimestampEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) =>
logEvent.AddPropertyIfAbsent(new LogEventProperty("UtcTimestamp",
new ScalarValue(logEvent.Timestamp.UtcDateTime)));
}
Comment on lines +27 to +32

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is your brain on OOP


/// <summary>
/// The log file setup that the client and the server share. tools/stepper reads the files of both,
/// so they must use the same line format.
/// </summary>
public static class SessionLog
{
/// <summary>
/// Each line starts with a monotonic stamp from <see cref="ElapsedEnricher"/>.
/// The wall time appears once, in the start line.
/// Each line starts with a UTC timestamp and a monotonic stamp from <see cref="ElapsedEnricher"/>.
/// </summary>
public const string FileTemplate =
"{Elapsed:F3} [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}";
"{UtcTimestamp:yyyy-MM-ddTHH:mm:ss.fffZ} ({Elapsed:F3}) [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}";

/// <summary>
/// A new log file path for this process, for example <c>openfreq-client-20260926-142120-12345.log</c>.
Expand Down Expand Up @@ -72,12 +81,14 @@ public static void DeleteOld(string logsDirectory, TimeSpan maxAge)
}

/// <summary>
/// Writes a log file in the <see cref="FileTemplate"/> format. Add an <see cref="ElapsedEnricher"/> to the logger too.
/// Writes a log file in the <see cref="FileTemplate"/> format.
/// Add an <see cref="ElapsedEnricher"/> and <see cref="UtcTimestampEnricher"/> to the logger too.
/// </summary>
/// <remarks>
/// Serilog 4 already uses the invariant culture when it has no format provider.
/// The explicit provider makes that a stated rule, because tools/stepper cannot read <c>139,700 MHz</c>.
/// </remarks>
public static LoggerConfiguration SessionFile(this LoggerSinkConfiguration writeTo, string path) =>
writeTo.File(path, outputTemplate: FileTemplate, formatProvider: CultureInfo.InvariantCulture);
public static LoggerConfiguration SessionFile(this LoggerSinkConfiguration writeTo, string path,
string outputTemplate = FileTemplate) =>
writeTo.File(path, outputTemplate: outputTemplate, formatProvider: CultureInfo.InvariantCulture);
}
3 changes: 2 additions & 1 deletion OpenFreq.Server/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ static async Task Main(string[] args)
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", "OpenFreqServer")
.Enrich.With(new ElapsedEnricher())
.Enrich.With(new UtcTimestampEnricher())
.WriteTo.SessionFile(logFile);

if (headlessMode)
Expand All @@ -53,7 +54,7 @@ static async Task Main(string[] args)
}

Log.Logger = loggerConfiguration.CreateLogger();
Log.Information("OpenFreq Server {Version} starting at {WallTime:o}", version, DateTimeOffset.Now);
Log.Information("OpenFreq Server {Version}", version);
SessionLog.DeleteOld(logsDirectory, TimeSpan.FromDays(30));

try
Expand Down
49 changes: 38 additions & 11 deletions tools/stepper/Parser.hs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import Data.Word
foldLog :: IO ByteString -> (StartLine -> IO s) -> (s -> LogLine -> IO s) -> IO (Either String s)
foldLog refill begin step = nextLine refill BS.empty >>= \case
Nothing -> pure $ Left "the input is empty, so it is not a session log"
Just (l, rest) -> case parseOnly (prefix *> startMessage) l of
Just (l, rest) -> case parseOnly parseStartLine l of
Left _ -> pure . Left $ mconcat [
"line 1 is not an OpenFreq start line, so the input is not a session log:\n ",
showLine l
Expand Down Expand Up @@ -84,17 +84,30 @@ readLine l = case parseOnly ((,) <$> prefix <*> takeByteString) l of
where
ptt t edge body = bimap (const BadPtt) (Just . Ptt) $ parseOnly (pttLine t edge) body

-- | The start of each line: the seconds since the app started, the level, and the source context.
-- ex: 8025.123 [INF] [OpenFreqClient.Services.OpenFreqService] PTT start: ...
prefix :: Parser Milli
prefix = do
seconds <- rational @Rational
-- | The start of each line: the monotonic seconds since the app started, the level, and the source context.
-- Also returns the wall time if present in the prefix.
-- ex: 2026-11-07T09:35:44.803Z (8025.123) [INF] [OpenFreqClient.Services.OpenFreqService] PTT start: ...
-- or: 8025.123 [INF] [OpenFreqClient.Services.OpenFreqService] PTT start: ...
prefixWithWall :: Parser (Maybe Text, Milli)
prefixWithWall = do
(wall, seconds) <- newPrefix <|> oldPrefix
_ <- string " ["
_ <- count 3 . satisfy $ inClass "A-Z"
_ <- string "] ["
_ <- takeTill (== ']')
_ <- string "] "
pure $ fromRational seconds
pure (wall, fromRational seconds)
where
newPrefix = do
wall <- isoTime
_ <- string " ("
s <- rational @Rational
_ <- char ')'
pure (Just wall, s)
oldPrefix = (Nothing,) <$> rational @Rational

prefix :: Parser Milli
prefix = snd <$> prefixWithWall

data Source = Client | Server
deriving stock (Show, Eq)
Expand All @@ -106,16 +119,30 @@ data StartLine = StartLine {
wallTime :: !Text
}

-- ex: OpenFreq Client 1.1.4 starting at 2026-09-26T14:21:20.0650000-04:00
startMessage :: Parser StartLine
startMessage = do
-- | Parse the first line of a session log.
-- ex: 2026-11-07T09:35:44.803Z (0.000) [INF] [OpenFreqClient] OpenFreq Client 1.1.4
-- or: 0.000 [INF] [OpenFreqClient] OpenFreq Client 1.1.4 starting at 2026-09-26T14:21:20.0650000-04:00
parseStartLine :: Parser StartLine
parseStartLine = do
(pfxWall, _) <- prefixWithWall
_ <- string "OpenFreq "
src <- (Client <$ string "Client") <|> (Server <$ string "Server")
ver <- char ' ' *> takeWhile1 (/= ' ')
wall <- string " starting at " *> isoTime
msgWall <- optional (string " starting at " *> isoTime)
endOfInput
let wall = fromMaybe (fromMaybe "unknown start time" pfxWall) msgWall
pure $ StartLine src (decodeUtf8Lenient ver) wall

-- ex: OpenFreq Client 1.1.4 starting at 2026-09-26T14:21:20.0650000-04:00
-- or: OpenFreq Client 1.1.4
startMessage :: Parser ()
startMessage = do
_ <- string "OpenFreq "
_ <- (Client <$ string "Client") <|> (Server <$ string "Server")
_ <- char ' ' *> takeWhile1 (/= ' ')
_ <- optional (string " starting at " *> isoTime)
endOfInput

-- | An ISO 8601 time with a UTC offset, without the fraction of a second.
-- ex: 2026-09-26T14:21:20.0650000-04:00 gives 2026-09-26 14:21:20 -04:00
isoTime :: Parser Text
Expand Down