pino#Logger TypeScript Examples
The following examples show how to use
pino#Logger.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From walletconnect-utils with MIT License | 7 votes |
export function getLoggerContext(
logger: Logger,
customContextKey: string = PINO_CUSTOM_CONTEXT_KEY
): string {
let context = "";
// logger.bindings is undefined in browser
if (typeof logger.bindings === "undefined") {
context = getBrowserLoggerContext(logger, customContextKey);
} else {
context = logger.bindings().context || "";
}
return context;
}
Example #2
Source File: server.ts From aurora-relayer with Creative Commons Zero v1.0 Universal | 6 votes |
export function createServer(
config: Config,
logger: Logger,
engine: Engine
): jayson.Server {
const server = new DatabaseServer(config, logger, engine);
const methodList = Object.getOwnPropertyNames(SkeletonServer.prototype)
.filter((id: string) => id !== 'constructor' && id[0] != '_')
.map((id: string) => [id, (server as any)[id]]);
const methodMap: MethodMap = Object.fromEntries(methodList);
const jaysonServer = new jayson.Server(methodMap, {
methodConstructor: Method,
useContext: server as any,
});
return jaysonServer;
}
Example #3
Source File: session.ts From walletconnect-v2-monorepo with Apache License 2.0 | 6 votes |
constructor(public client: IClient, public logger: Logger) {
super(client, logger);
this.logger = generateChildLogger(logger, this.name);
this.pending = new Store<SessionTypes.Pending>(client, this.logger, this.config.status.pending);
this.settled = new Store<SessionTypes.Settled>(client, this.logger, this.config.status.settled);
this.history = new JsonRpcHistory(this.logger, this.client.storage);
this.expirer = new Expirer(client, this.logger);
this.engine = new Engine(this) as SessionTypes.Engine;
}
Example #4
Source File: app.ts From aurora-relayer with Creative Commons Zero v1.0 Universal | 6 votes |
export async function createApp(
config: Config,
logger: Logger,
engine: Engine
): Promise<any> {
const app = express();
app.disable('x-powered-by');
app.use(middleware.setRequestID());
app.use(middleware.blacklistIPs());
app.use(bodyParser.json({ type: 'application/json' }));
app.use(middleware.logger(logger));
app.use(cors()); // Access-Control-Allow-Origin: *
app.get('/health', (req, res) => {
res.send('OK');
});
app.get('/metrics', (req, res) => {
res.send(''); // TODO
});
app.use(rpcMiddleware(createServer(config, logger, engine)));
app.use(middleware.handleErrors());
await createWsServer(config, logger, engine, app);
return app;
}
Example #5
Source File: app.ts From one-platform with MIT License | 6 votes |
setupMongoose = async (mongoURI: string, logger: Logger) => {
/* Setup database connection */
try {
await mongoose.connect(mongoURI);
logger.info('Connected to database');
} catch (error) {
logger.error(error, 'Failed to connect to database');
process.exit(1);
}
}
Example #6
Source File: validate.ts From payload with MIT License | 6 votes |
validateSchema = (config: SanitizedConfig, logger: Logger): SanitizedConfig => {
const result = schema.validate(config, {
abortEarly: false,
});
const nestedErrors = [
...validateCollections(config.collections),
...validateGlobals(config.globals),
];
if (result.error || nestedErrors.length > 0) {
logger.error(`There were ${(result.error?.details?.length || 0) + nestedErrors.length} errors validating your Payload config`);
let i = 0;
if (result.error) {
result.error.details.forEach(({ message }) => {
i += 1;
logger.error(`${i}: ${message}`);
});
}
nestedErrors.forEach((message) => {
i += 1;
logger.error(`${i}: ${message}`);
});
process.exit(1);
}
return result.value;
}
Example #7
Source File: pairing.ts From walletconnect-v2-monorepo with Apache License 2.0 | 6 votes |
constructor(public client: IClient, public logger: Logger) {
super(client, logger);
this.logger = generateChildLogger(logger, this.name);
this.pending = new Store<PairingTypes.Pending>(client, this.logger, this.config.status.pending);
this.settled = new Store<PairingTypes.Settled>(client, this.logger, this.config.status.settled);
this.history = new JsonRpcHistory(this.logger, this.client.storage);
this.expirer = new Expirer(client, this.logger);
this.engine = new Engine(this) as PairingTypes.Engine;
}
Example #8
Source File: utils.ts From walletconnect-utils with MIT License | 6 votes |
export function getBrowserLoggerContext(
logger: Logger,
customContextKey: string = PINO_CUSTOM_CONTEXT_KEY
): string {
return (logger as any)[customContextKey] || "";
}
Example #9
Source File: middleware.d.ts From aurora-relayer with Creative Commons Zero v1.0 Universal | 5 votes |
export declare function logger(logger: Logger): any;
Example #10
Source File: encoder.ts From walletconnect-v2-monorepo with Apache License 2.0 | 5 votes |
constructor(public client: IClient, public logger: Logger) {
this.client = client;
this.logger = generateChildLogger(logger, this.name);
}
Example #11
Source File: ws_server.d.ts From aurora-relayer with Creative Commons Zero v1.0 Universal | 5 votes |
export declare function createWsServer(config: Config, logger: Logger, engine: Engine, app: any): Promise<boolean>;
Example #12
Source File: crypto.ts From walletconnect-v2-monorepo with Apache License 2.0 | 5 votes |
constructor(public client: IClient, public logger: Logger) {
this.client = client;
this.logger = generateChildLogger(logger, this.name);
}
Example #13
Source File: 2021-12-02-event.d.ts From aurora-relayer with Creative Commons Zero v1.0 Universal | 5 votes |
readonly logger: Logger;
Example #14
Source File: heartbeat.ts From walletconnect-v2-monorepo with Apache License 2.0 | 5 votes |
public logger: Logger;
Example #15
Source File: index.test.ts From walletconnect-utils with MIT License | 5 votes |
describe("Logger", () => {
let logger: Logger;
before(() => {
logger = pino(getDefaultLoggerOptions());
});
it("init", () => {
chai.expect(logger).to.not.be.undefined;
});
it("context", async () => {
const alphaContext = "alpha";
const alphaContextResult = formatChildLoggerContext(logger, alphaContext);
const alphaContextExpected = alphaContext;
chai.expect(alphaContextResult).to.eql(alphaContextExpected);
const alpha = generateChildLogger(logger, alphaContext);
chai.expect(alpha.custom_context).to.not.be.undefined;
chai.expect(alpha.custom_context).to.eql(alphaContextExpected);
chai.expect(alpha.bindings().context).to.eql(alphaContextExpected);
chai.expect(alphaContextResult).to.eql(alphaContextExpected);
const betaContext = "beta";
const betaContextResult = formatChildLoggerContext(alpha, betaContext);
const betaContextExpected = alphaContextExpected + "/" + betaContext;
chai.expect(betaContextResult).to.eql(betaContextExpected);
const beta = generateChildLogger(alpha, betaContext);
chai.expect(beta.custom_context).to.not.be.undefined;
chai.expect(beta.custom_context).to.eql(betaContextExpected);
chai.expect(beta.bindings().context).to.eql(betaContextExpected);
chai.expect(betaContextResult).to.eql(betaContextExpected);
const gammaContext = "gamma";
const gammaContextExpected = betaContextExpected + "/" + gammaContext;
const gammaContextResult = formatChildLoggerContext(beta, gammaContext);
chai.expect(gammaContextResult).to.eql(gammaContextExpected);
const gamma = generateChildLogger(beta, gammaContext);
chai.expect(gamma.custom_context).to.not.be.undefined;
chai.expect(gamma.custom_context).to.eql(gammaContextExpected);
chai.expect(gamma.bindings().context).to.eql(gammaContextExpected);
chai.expect(gammaContextResult).to.eql(gammaContextExpected);
});
});
Example #16
Source File: skeleton.ts From aurora-relayer with Creative Commons Zero v1.0 Universal | 5 votes |
constructor(
public readonly config: Config,
public readonly logger: Logger,
public readonly engine: Engine
) {
this._init();
}
Example #17
Source File: puppeteer.ts From epicgames-freegames-node with MIT License | 5 votes |
retryFunction = async <T>(
f: () => Promise<T>,
L: Logger,
outputName: string,
attempts = 0
): Promise<T> => {
const TIMEOUT = config.browserLaunchTimeout * 1000;
const MAX_ATTEMPTS = config.browserLaunchRetryAttempts;
const beforeProcesses = await pidtree(process.pid);
const newPageCancelable = cancelable(f());
let timeoutInstance: NodeJS.Timeout | undefined;
const res = await Promise.race([
newPageCancelable,
new Promise((resolve) => {
timeoutInstance = setTimeout(resolve, TIMEOUT);
}).then(() => 'timeout'),
]);
if (typeof res !== 'string') {
if (timeoutInstance) clearTimeout(timeoutInstance);
return res;
}
newPageCancelable.cancel();
const afterProcesses = await pidtree(process.pid);
const newProcesses = await Promise.all(
afterProcesses
.filter((p) => !beforeProcesses.includes(p))
.map(async (p) => (await findProcess('pid', p))[0])
);
const chromiumProcesses = newProcesses.filter(
(p) =>
p !== undefined && ['chromium', 'chrome', 'headless_shell'].some((n) => p.name.includes(n))
);
L.debug({ chromiumProcesses }, 'Killing new browser processes spawned');
chromiumProcesses.forEach((p) => process.kill(p.pid));
if (attempts >= MAX_ATTEMPTS) {
L.error(
`If not already, consider using the Debian (:bullseye-slim) version of the image. More: https://github.com/claabs/epicgames-freegames-node#docker-configuration`
);
throw new Error(`Could not do ${outputName} after ${MAX_ATTEMPTS + 1} failed attempts.`);
}
L.warn(
{ attempts, MAX_ATTEMPTS },
`${outputName} did not work after ${TIMEOUT}ms. Trying again.`
);
return retryFunction(f, L, outputName, attempts + 1);
}
Example #18
Source File: apolloLogger.ts From cloud-pricing-api with Apache License 2.0 | 5 votes |
constructor(private logger: Logger) {}
Example #19
Source File: index.spec.ts From pino-lambda with MIT License | 5 votes |
/**
* Creates a test logger and output buffer for assertions
* Returns the logger and the buffer
*
* CAUTION:
* Usage defined below is for the purposes of the Test Harness
* and is not reflective of the actual usage of pino-lambda
*/
function createLogger(
options?: LoggerOptions,
mixedOptions?: LambdaRequestTrackerOptions & PinoLambdaOptions,
): {
log: Logger;
output: { buffer: string };
withRequest: (event: LambdaEvent, context: LambdaContext) => void;
} {
const output = {
buffer: 'undefined',
};
const destination = pinoLambdaDestination({
...mixedOptions,
streamWriter: (str: string | Uint8Array): boolean => {
output.buffer = (str as string).trim();
return true;
},
});
const log = pino(
{
base: null,
...options,
},
destination,
);
const withRequest = lambdaRequestTracker({
...mixedOptions,
});
return { log, output, withRequest };
}
Example #20
Source File: logger.ts From one-platform with MIT License | 5 votes |
setupLogger = (): Logger<LoggerOptions> => {
const logger = pino();
return logger;
}
Example #21
Source File: history.ts From walletconnect-v2-monorepo with Apache License 2.0 | 5 votes |
constructor(public logger: Logger, public storage: IRelayerStorage) {
super();
}
Example #22
Source File: setup.ts From cognito-local with MIT License | 4 votes |
withCognitoSdk =
(
fn: (
cognito: () => AWS.CognitoIdentityServiceProvider,
dataStoreFactory: () => DataStoreFactory
) => void,
{
logger = MockLogger as any,
clock = new DateClock(),
}: { logger?: Logger; clock?: Clock } = {}
) =>
() => {
let dataDirectory: string;
let httpServer: http.Server;
let cognitoSdk: AWS.CognitoIdentityServiceProvider;
let dataStoreFactory: DataStoreFactory;
beforeEach(async () => {
dataDirectory = await mkdtemp("/tmp/cognito-local:");
const ctx = { logger };
dataStoreFactory = new StormDBDataStoreFactory(
dataDirectory,
new NoOpCache()
);
const cognitoServiceFactory = new CognitoServiceFactoryImpl(
dataDirectory,
clock,
dataStoreFactory,
new UserPoolServiceFactoryImpl(clock, dataStoreFactory)
);
const cognitoClient = await cognitoServiceFactory.create(ctx, {});
const triggers = new TriggersService(
clock,
cognitoClient,
{
enabled: jest.fn().mockReturnValue(false),
invoke: jest.fn(),
},
new CryptoService({ KMSKeyId: "", KMSKeyAlias: "" })
);
const router = Router({
clock,
cognito: cognitoClient,
config: DefaultConfig,
messages: new MessagesService(triggers, newMockMessageDelivery()),
otp,
triggers,
tokenGenerator: new JwtTokenGenerator(
clock,
triggers,
DefaultConfig.TokenConfig
),
});
const server = createServer(router, ctx.logger);
httpServer = await server.start({
port: 0,
});
const address = httpServer.address();
if (!address) {
throw new Error("HttpServer has no address");
}
const url =
typeof address === "string"
? address
: `${address.address}:${address.port}`;
cognitoSdk = new AWS.CognitoIdentityServiceProvider({
credentials: {
accessKeyId: "local",
secretAccessKey: "local",
},
region: "local",
endpoint: `http://${url}`,
});
});
fn(
() => cognitoSdk,
() => dataStoreFactory
);
afterEach((done) => {
httpServer.close(() => {
rmdir(dataDirectory, {
recursive: true,
}).then(done, done);
});
});
}
Example #23
Source File: setupCronTask.ts From one-platform with MIT License | 4 votes |
setupCronTask = (
jobs: Agenda,
logger: Logger,
config: Config,
mailer: Transporter<SMTPTransport.SentMessageInfo>,
) => {
/**
* This is the parent task which runs exactly 12am
* It goes through all env and spin up another queue called child with required data
*/
jobs.define(Jobs.SUBSCRIPTION_PARENT, { concurrency: 1 }, async () => {
logger.info('Cron task for subscriptions started');
const totalNamespace = await Namespace.count();
const perDoc = 20;
const numberOfCycles = Math.ceil(totalNamespace / perDoc);
for (let i = 1; i <= numberOfCycles; i += 1) {
const nsDocs = await Namespace.find()
.sort([['createdOn', -1]])
.limit(perDoc)
.skip(perDoc * (i - 1))
.lean();
nsDocs.forEach((doc) => {
doc.schemas.forEach((schema) => {
if (schema.flags.isDeprecated) return;
schema.environments.forEach((env) => {
if (!env.schemaEndpoint) {
return;
}
jobs.now(Jobs.SUBSCRIPTION_CHILD, {
namespace: { id: doc._id, name: doc.name },
schema: { id: schema._id, name: schema.name, category: schema.category },
env,
});
});
});
});
}
logger.info('Cron task for subscriptions ended');
});
/**
* Child process that handles diff finding and mailing
*/
jobs.define(Jobs.SUBSCRIPTION_CHILD, { concurrency: 10 }, async (job: Job) => {
logger.info(`triggered job: ${job.attrs._id}`);
const { data } = job.attrs;
if (!data) return;
const { namespace, schema, env } = data;
const subLog = logger.child({
namespace: namespace.id,
schema: schema.id,
envId: env._id,
name: env.name,
});
const headers = env?.headers?.map(({ key, value }: { key: string; value: string }) => ({
key,
value: decrypt(config.decryptionKey, value),
}));
const res = await fetchSchema(data.schema.category, env.schemaEndpoint, headers);
const resBase64 = Buffer.from(res).toString('base64');
const store = await SpecStore.findOne({
namespaceId: namespace.id,
schemaId: schema.id,
environmentId: env._id,
})
.sort([['createdOn', -1]])
.lean();
/**
* Spec is not added, therefore not needed to do any furthur process
* Just store it
*/
if (!store) {
subLog.info('API not added yet');
await saveSpecSheet(namespace.id, schema.id, env._id, resBase64);
return;
}
const oldSpec = Buffer.from(store.spec, 'base64').toString();
/**
* Check for graphql API
* Using inspector compare two schemas
* If there is a change store new schema
* Send mail with new changes denoted
*/
if (data.schema.category === IApiCategory.Graphql) {
try {
const gqlDiff = await diffGraphql(oldSpec, res);
if (!gqlDiff.hasChanged) {
subLog.info('GQL API not changed');
return;
}
subLog.info('GQL API changed');
await saveSpecSheet(namespace.id, schema.id, env._id, resBase64);
const subscribers = await getSubscribersOfAnEnv(namespace.id, schema.id, env._id);
if (!subscribers.length) {
subLog.info('No subscribers found!!!');
return;
}
await mailer.sendMail({
from: 'One Platform | API Catalog<[email protected]>',
to: subscribers.map((el) => el.subscriberEmail),
subject: `API updates for ${env.name.toUpperCase()} environment of
${schema.name.toUpperCase()} in ${namespace.name.toUpperCase()} namespace`,
html: gqlApiTemplate({
...gqlDiff,
namespace: namespace.name,
schema: schema.name,
environment: env.name,
}),
});
subLog.info('Mail send to subscribers');
} catch (error) {
subLog.error(error?.message);
}
return;
}
/**
* Else case: REST API
* Check for openapi difference
* Send mail to subscribers of any change classified into breaking and non breaking
*/
try {
const diff = await diffOpenAPI(oldSpec, res);
if (!diff.hasChanged) {
subLog.info({ name: env.name }, 'Rest API not changed');
return;
}
subLog.info('REST API changed');
await saveSpecSheet(namespace.id, schema.id, env._id, resBase64);
const subscribers = await getSubscribersOfAnEnv(namespace.id, schema.id, env._id);
if (!subscribers.length) {
subLog.info('No subscribers found!!!');
return;
}
await mailer.sendMail({
from: 'One Platform | API Catalog<[email protected]>',
to: subscribers.map((el) => el.subscriberEmail),
subject: `API updates for ${env.name.toUpperCase()} environment of
${schema.name.toUpperCase()} in ${namespace.name.toUpperCase()} namespace`, // Subject line
html: restApiTemplate({
...diff,
namespace: namespace.name,
schema: schema.name,
environment: env.name,
}),
});
subLog.info('Mail send');
} catch (error) {
subLog.error(error);
}
});
jobs.on(`fail:${Jobs.SUBSCRIPTION_CHILD}`, (err, job: Job) => {
logger.error(`Failed to execute job: ${job.attrs._id}`);
logger.error(job.attrs.data?.env?.name);
logger.error(err);
});
jobs.start();
jobs.on('ready', async () => {
await jobs.every('0 1 * * *', Jobs.SUBSCRIPTION_PARENT);
});
}