Skip to content

SmrtHub.Logging

Assembly: SmrtHub.Logging

Namespace: SmrtHub.Logging

ActivityEnricher

Enriches log events with W3C trace context from System.Diagnostics.Activity

ActivityScope

Disposable scope for Activity-based tracing that stops the activity when disposed

Methods

AddBaggage(string param0, string param1)

Adds baggage to the current activity.

AddTag(string param0, object param1)

Adds a tag to the current activity.

Dispose()

Stops the activity and logs its completion.

SetStatus(string param0, string param1)

Sets status of the current activity.

Propertys

Activity

Gets the underlying Activity if available.

Logger

Centralized logger for SmrtHub apps. Enterprise-grade: structured logging, correlation scopes, dynamic levels, size/time rolling, basic PII scrubbing, metrics, safe init/shutdown, and HTML export.

Methods

BeginActivity(string name, string activityKind, Collections.Generic.IDictionary tags)

Begin a new Activity for distributed tracing. When disposed, the Activity is stopped and its data is automatically included in log entries via the ActivityEnricher.

Parameters

  • name — Name of the activity/operation
  • activityKind — Kind of activity as a string ("Server", "Client", "Producer", "Consumer", "Internal")
  • tags — Optional tags to add to the activity

Returns: A disposable ActivityScope that stops the activity when disposed

BeginCorrelation(string correlationId, bool createActivityIfMissing, string activityName)

Begin a correlation scope: sets the ambient CorrelationId and, optionally, creates an Activity when missing. Disposing restores the previous CorrelationId and stops any created Activity.

Parameters

  • correlationId — Explicit correlation id; if null/empty, uses current Activity.TraceId or a new one.
  • createActivityIfMissing — If true and no Activity is present, start a new one (requires EnableTraceContext).
  • activityName — Name of the created Activity when applicable.
BeginScope(string param0, Collections.Generic.IDictionary param1)

Begin a named scope with optional properties. Dispose to end the scope.

ConfigureFrom(Microsoft.Extensions.Configuration.IConfiguration param0, string param1, string param2)

Configure logger from Microsoft.Extensions.Configuration. Reads options from a section (default: "Logging:SmrtHub").

ConfigureFrom(SmrtHub.Config.Logging.SmrtLoggingOptions param0, string param1)

[DEPRECATED] Configure logger from a typed options object from Smrt.Config. Prefer SmrtHub.Logging.Logger.ConfigureFrom(Microsoft.Extensions.Configuration.IConfiguration,System.String,System.String) so configuration lives only in appsettings. This overload remains for legacy/tests and will be removed in a future release.

Debug(string param0)

Log a debug message.

Debug(string param0, object[] param1)

Log a debug with template and args.

DebugAsync(string param0)

Log debug asynchronously.

EnableTestMode()

Enable test mode which changes how the logger behaves to support unit testing. This should be called before any tests run.

EnsureInitialized()

Ensure the logger is initialized using the standard auto-configuration path. Safe to call many times; does nothing if already configured.

Error(Exception param0, string param1, object[] param2)

Log an error with template and exception.

Error(string param0, Exception param1)

Log an error message, optionally with exception.

ErrorAsync(string param0, Exception param1)

Log error asynchronously.

ExportHtmlLog(bool? autoOpen, int maxEntries)

Export the JSON log to a simple HTML page for quick viewing.

Parameters

  • autoOpen — Whether to automatically open the exported HTML file. Defaults to null, which uses the option from LoggerOptions.
  • maxEntries — Maximum number of log entries to include. Default is 1000.

Returns: Path to the exported HTML file, or empty string if export failed.

ExportUnifiedHtmlLogs(bool? param0, int param1)

Export a unified HTML log viewer that allows switching between all component logs found under the logs root.

Fatal(Exception param0, string param1, object[] param2)

Log a fatal with template and exception.

Fatal(string param0, Exception param1)

Log a fatal message, optionally with exception.

FatalAsync(string param0, Exception param1)

Log fatal asynchronously.

Flush()

Flush log buffers (no-op for Serilog; provided for API completeness).

ForComponent(string param0)

Creates or returns a cached logger dedicated to a specific component slug.

GetActivityTagPrefix()

Get the configured Activity Tag property prefix. Empty means use raw tag keys.

GetCorrelationId()

Get the ambient correlation id for the current async context.

GetLogFilePaths()

Get current log file paths for text, JSON and HTML.

GetMetrics()

Get metrics about logger activity and performance.

Returns: A snapshot of current logging statistics

GetTraceContext()

Get current W3C trace context IDs if an Activity is active.

Info(string param0)

Log an information message.

Info(string param0, object[] param1)

Log an information message with template and args.

InfoAsync(string param0)

Log information asynchronously.

Initialize(string param0, Serilog.Events.LogEventLevel? param1, SmrtHub.Logging.Logger.LoggerOptions param2)

Initialize the logger for a given component. Safe to call multiple times; reconfigures sinks.

InjectExportHtmlPathForTests(string param0)

Test helper to inject a custom HTML export path. No-op outside test mode.

IsEnabled(Serilog.Events.LogEventLevel param0)

Check if logging is enabled at the specified level.

MakeTraceparent()

Create a W3C traceparent header for the current Activity.

PersistMinimumLevel(Serilog.Events.LogEventLevel level, Microsoft.Extensions.Configuration.IConfiguration configuration, string sectionPath)

Dynamically set and persist the minimum log level to configuration (if supported). This ensures that the level change survives application restarts.

Parameters

  • level — The new minimum log level
  • configuration — The IConfiguration instance to update
  • sectionPath — Path to the SmrtHub logging section (default: "Logging:SmrtHub")

Returns: True if the level was successfully persisted, false otherwise

PushProperty(string param0, object param1)

Push a contextual property for the lifetime of the returned scope.

ResetForTesting()

Reset the logger state for testing purposes. This is an advanced method that should only be used in test scenarios.

SetCorrelationId(string param0)

Set the ambient correlation id for the current async context.

SetMinimumLevel(Serilog.Events.LogEventLevel param0)

Dynamically set the minimum log level.

Shutdown()

Shutdown the logger and dispose sinks.

TryApplyLogDirectoryPermissions(string param0, SmrtHub.Logging.Logger.LoggerOptions param1)

Apply appropriate access permissions to the log directory

Verbose(string param0)

Log a verbose message.

Verbose(string param0, object[] param1)

Log a verbose with template and args.

VerboseAsync(string param0)

Log verbose asynchronously.

Warning(string param0)

Log a warning message.

Warning(string param0, object[] param1)

Log a warning with template and args.

WarningAsync(string param0)

Log warning asynchronously.

LoggingExtensions

Extension methods for SmrtHub.Logging functionality to simplify common patterns.

Methods

LogException(Exception exception, string message, object[] args)

Logs an exception with enriched context and returns the exception for re-throwing

Parameters

  • exception — The exception to log
  • message — Optional message template explaining the context
  • args — Format arguments for the message template

Returns: The original exception for re-throwing

LogOperation(string operationName, Collections.Generic.IDictionary properties)

Creates a scope for a unit of work that automatically logs start and end messages

Parameters

  • operationName — Name of the operation being performed
  • properties — Optional additional properties to include in logs

Returns: A disposable scope that logs completion or failure on dispose

LogTiming(Action action, string operationName, string category, Collections.Generic.IDictionary properties)

Executes an action with timing measurement and logs the elapsed time with details.

Parameters

  • action — The action to execute and time
  • operationName — Name of the operation being timed
  • category — Optional category for the operation
  • properties — Optional additional properties to log
LogTiming(Func<``0> func, string operationName, string category, Collections.Generic.IDictionary properties)

Executes a function with timing measurement and logs the elapsed time with details.

Parameters

  • func — The function to execute and time
  • operationName — Name of the operation being timed
  • category — Optional category for the operation
  • properties — Optional additional properties to log

Returns: Result of the executed function

LogTimingAsync(Func action, string operationName, string category, Collections.Generic.IDictionary properties)

Executes an async action with timing measurement and logs the elapsed time with details.

Parameters

  • action — The async action to execute and time
  • operationName — Name of the operation being timed
  • category — Optional category for the operation
  • properties — Optional additional properties to log
LogTimingAsync(Func<Threading.Tasks.Task<``0>> func, string operationName, string category, Collections.Generic.IDictionary properties)

Executes an async function with timing measurement and logs the elapsed time with details.

Parameters

  • func — The async function to execute and time
  • operationName — Name of the operation being timed
  • category — Optional category for the operation
  • properties — Optional additional properties to log

Returns: Result of the executed async function

StructuredRedactionEnricher

Enricher that performs structured redaction on log event properties. - Redacts values for sensitive property names (e.g., password, token) - Applies regex-based Sanitize() to string scalars - Recurses through sequences, dictionaries, and structures

TestSinkExtensions

Extensions for Serilog to support testing

Methods

ClearEvents()

Clear all captured log events

GetCapturedEvents()

Retrieve captured log events for test assertions

Returns: A copy of all captured log events

TestCoreSink(Serilog.Configuration.LoggerSinkConfiguration param0, Serilog.Formatting.ITextFormatter param1)

A special sink used for testing that avoids the Serilog CreateLogger limitation

UseLocalSink(bool param0)

Set this to true when we want to use TestSinkExtensionsLocal

Namespace: SmrtHub.Logging.Logger

ComponentLogger

Component-specific logger that writes to dedicated sinks while honoring global logging policies.

Methods

Debug(string param0, string param1, string param2, int param3)

Log a debug message.

Debug(string param0, string param1, string param2, int param3, object[] param4)

Log a debug template with args.

Dispose()

Dispose logger sinks when they are owned by the component logger.

Error(Exception param0, string param1, string param2, string param3, int param4, object[] param5)

Log an error template with exception and args.

Error(string param0, Exception param1, string param2, string param3, int param4)

Log an error message.

Fatal(Exception param0, string param1, string param2, string param3, int param4, object[] param5)

Log a fatal template with exception.

Fatal(string param0, Exception param1, string param2, string param3, int param4)

Log a fatal message.

Info(string param0, string param1, string param2, int param3)

Log an information message.

Info(string param0, string param1, string param2, int param3, object[] param4)

Log an information message with template and args.

Verbose(string param0, string param1, string param2, int param3)

Log a verbose message.

Verbose(string param0, string param1, string param2, int param3, object[] param4)

Log a verbose template with args.

Warning(string param0, string param1, string param2, int param3)

Log a warning message.

Warning(string param0, string param1, string param2, int param3, object[] param4)

Log a warning message with template and args.

Propertys

ComponentSlug

The normalized component slug this logger writes under.

LoggerMetrics

Logger metrics representing current logging activity and configuration.

Propertys

BackpressureCircuitActive

Whether the backpressure circuit breaker is currently dropping sub-warning events.

BackpressureCircuitHoldSecondsRemaining

Approximate seconds remaining before the backpressure circuit closes.

ComponentName

Current component name.

ConsoleEnabled

Whether console output is enabled.

DebugCount

Count of Debug level events.

DroppedEvents

Count of events dropped due to errors.

Enqueued

Total events enqueued into the async buffer (if enabled).

ErrorCount

Count of Error level events.

FatalCount

Count of Fatal level events.

InformationCount

Count of Information level events.

LastErrorTime

UTC timestamp of the last error event.

LogDirectory

Current log directory.

MinimumLevel

Current minimum log level.

ScrubPiiEnabled

Whether PII scrubbing is enabled.

TotalEvents

Total log events written.

TraceContextEnabled

Whether W3C trace context is enabled.

VerboseCount

Count of Verbose level events.

WarningCount

Count of Warning level events.

Written

Total events written to sinks (sync + async).

LoggerOptions

Options controlling logger behavior and sinks.

Propertys

ActivityTagPrefix

Prefix applied to Activity Tag properties when enriched (default: "Tag."). Use empty string to emit raw tag keys.

AutoOpenHtmlExport

Auto-open HTML logs when exported.

BackpressureCircuitHoldSeconds

When tripped, duration in seconds to drop messages below Warning. Default: 60.

BackpressureFlipToWarning

Whether to enable circuit behavior (drop below Warning during pressure). Default: true.

BackpressureThresholdDrops

Minimum dropped events within a window to count as a high-drop window. Default: 50.

BackpressureTripWindows

Number of consecutive high-drop windows required to trip the circuit. Default: 3.

BackpressureWindowSeconds

Backpressure sampling window in seconds (async mode only). Default: 10.

Default

Default instance.

EnableConsole

Enable console output (useful for development).

EnableOtelFields

Emit OTEL-friendly duplicate fields (trace_id/span_id/parent_span_id). Default: false.

EnableStructuredRedaction

Enable structured property redaction via an enricher. Default: true.

EnableTraceContext

Enable W3C trace context propagation.

EnrichWithDemystifiedExceptions

Enrich with exception demystifier for better stack traces.

FileNameMode

File naming mode: "shared" (default) or "per-process" to suffix -pid{n}.

FileSizeLimitBytes

Max file size before rolling.

LogDirectory

Root directory for logs; if empty, uses %LocalAppData%/SmrtHub/Logs/{component}.

MaxQueueSize

Optional max queue size for async buffering; null or <= 0 means synchronous writes.

OnDropPolicy

Queue policy when full: "block" to block producer; otherwise drops newest.

RedactionToken

Replacement token for redacted text.

RetainedFileCountLimit

Maximum retained files per sink.

RollOnFileSizeLimit

Whether to roll on file size limit.

ScrubPII

PII scrubbing on/off.

SecureLogAcls

Harden Windows ACLs for the log directory to SYSTEM + current user only. Default: false.

WriterThrottleMs

Optional writer throttle in milliseconds to slow down the background writer (useful for tests). Default: 0 (no delay).

LoggerStats

Aggregated counters for logged events.

Methods

Clone()

Create a snapshot copy of the current counters.

Increment(Serilog.Events.LogEventLevel param0)

Increment counters for a specific log level.

IncrementDropped()

Increment the count of dropped writes due to failures.

IncrementEnqueued()

Increment the count of events enqueued (async mode only).

IncrementWritten()

Increment the count of events successfully written.

Propertys

Debug

Debug level count.

Dropped

Dropped write count.

Enqueued

Enqueued events count.

Error

Error level count.

FatalCount

Fatal level count.

Information

Information level count.

LastErrorUtc

UTC timestamp of last error logged.

Total

Total number of log writes.

VerboseCount

Verbose level count.

Warning

Warning level count.

Written

Written events count.

Namespace: SmrtHub.Logging.TestSinkExtensions

TestLogSink

In-memory sink for testing