Skip to content

Commit

Permalink
feat: add network context to logs (#163)
Browse files Browse the repository at this point in the history
* feat: add network context to logs

This commit adds an optional context object to MetricsLogger which can be used
to add network id and network name to all logs. This may help alerting services
differentiate and bucket errors by network

Example log after this change
```
{"name":"Uniswap Smart Order Router",
"hostname":"toda-XPS-15-9510",
"pid":157780,
"chainId":1,
"networkName":"mainnet",
"level":30,
"key":"FindBestSwapRoute",
"value":13,
"unit":"Milliseconds",
"msg":"[Metric]: FindBestSwapRoute: 13 | Milliseconds",
"time":"2022-08-17T19:40:45.340Z",
"v":0}
```

* fix: remove lint changes
  • Loading branch information
marktoda authored Aug 28, 2022
1 parent 233aa5e commit d686a14
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
10 changes: 7 additions & 3 deletions cli/base-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
GasPrice,
ID_TO_CHAIN_ID,
ID_TO_PROVIDER,
ID_TO_NETWORK_NAME,
IRouter,
ISwapToRatio,
ITokenProvider,
Expand Down Expand Up @@ -207,12 +208,15 @@ export abstract class BaseCommand extends Command {
setGlobalLogger(this.logger);
}

const metricLogger: MetricLogger = new MetricLogger();
setGlobalMetric(metricLogger);

const chainId = ID_TO_CHAIN_ID(chainIdNumb);
const chainProvider = ID_TO_PROVIDER(chainId);

const metricLogger: MetricLogger = new MetricLogger({
chainId: chainIdNumb,
networkName: ID_TO_NETWORK_NAME(chainId)
});
setGlobalMetric(metricLogger);

const provider = new JsonRpcProvider(chainProvider, chainId);
this._blockNumber = await provider.getBlockNumber();

Expand Down
18 changes: 14 additions & 4 deletions src/util/metric.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { log, setGlobalLogger } from './log';
import Logger from 'bunyan';

import { log } from './log';

export enum MetricLoggerUnit {
Seconds = 'Seconds',
Expand Down Expand Up @@ -35,17 +37,25 @@ export abstract class IMetric {
abstract putMetric(key: string, value: number, unit?: MetricLoggerUnit): void;
}

interface MetricContext {
chainId: number;
networkName: string;
}

export class MetricLogger extends IMetric {
constructor() {
private log: Logger;

constructor(context?: MetricContext) {
super();
this.log = log.child(context || {});
}

public putDimensions(dimensions: Record<string, string>): void {
setGlobalLogger(log.child(dimensions));
this.log = this.log.child(dimensions);
}

public putMetric(key: string, value: number, unit?: MetricLoggerUnit): void {
log.info(
this.log.info(
{ key, value, unit },
`[Metric]: ${key}: ${value} | ${unit ? unit : ''}`
);
Expand Down

0 comments on commit d686a14

Please sign in to comment.