Implementing QuickFix/n Logging with NLog
Wen working with QuickFix/n ibrary , efficient logging is crucial for troubleshooting. Here's how to implement a custom logging solution that routes QuickFix logs through NLog to your ELK stack.
Key Components
- NLogAdapter: A custom adapter that implements QuickFix's
ILog
interface:
public class NLogAdapter(ILogger logger) : ILog
{
private const string HeartbeatPattern = @"\x0135=0\x01";
private static readonly Regex HeartbeatRegex = new(HeartbeatPattern, RegexOptions.Compiled);
private static bool IsHeartBeat(string message) => HeartbeatRegex.IsMatch(message);
public void OnIncoming(string message)
{
if (!IsHeartBeat(message))
{
logger.Info("Incoming: {Message}", message);
}
}
// ... other implementations
}
- NLogQuickFixLogFactory: A factory class to create log instances:
public class NLogQuickFixLogFactory(ILog logger) : ILogFactory
{
public ILog Create(SessionID sessionId) => logger;
public ILog CreateNonSessionLog() => logger;
}
Implementation Steps
- Register Dependencies in your DI container:
builder.Services.AddSingleton<NLog.ILogger>(_ => LogManager.GetCurrentClassLogger());
builder.Services.AddSingleton<ILog, NLogAdapter>();
builder.Services.AddSingleton<ILogFactory, NLogQuickFixLogFactory>();
- Configure QuickFix to use the custom logger:
var initiator = new SocketInitiator(
clientApp,
storeFactory,
sessionSettings,
new NLogQuickFixLogFactory(quickfixLogger) // Use custom logger injeted by ILog here
);
Key Features
- Heartbeat Filtering: Reduces log noise by filtering out FIX heartbeat messages
- Structured Logging: Uses NLog's structured logging format for better parsing in ELK
- Separation of Concerns: Cleanly separates QuickFix logging from application logging
Benefits
- Centralized logging in ELK stack
- Better debugging apabilities
- Reduced log volume through heartbeat filtering
- Consistent logging format across your application