Skip to content

Commit

Permalink
.prettierrc: set printWidth to 120 (#103)
Browse files Browse the repository at this point in the history
  • Loading branch information
PetrHeinz authored Jan 5, 2024
1 parent 4060622 commit aab5429
Show file tree
Hide file tree
Showing 21 changed files with 63 additions and 264 deletions.
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"printWidth": 120,
"trailingComma": "all",
"tabWidth": 2,
"semi": true,
Expand Down
25 changes: 9 additions & 16 deletions example-project/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,22 @@ const logger = new Logtail(process.argv[2], { sendLogsToConsoleOutput: true });
// Usage

// Send debug level log using the debug() method
const debugLog = logger.debug(
`I am using Better Stack! (${process.title} v${
process.versions?.[process.title]
})`,
);
const debugLog = logger.debug(`I am using Better Stack! (${process.title} v${process.versions?.[process.title]})`);

// Send info level log using the info() method
const infoLog = logger.info("An interesting event occurred!");

// Send warn level log using the warn() method
// You can add additional structured data to help you troubleshoot your code as shown below
const warningLog = logger.warn(
"Something is not quite right, better check on it.",
{
user: {
username: "someuser",
email: "[email protected]",
},
additional_info: {
tried_accessing: "/url/of/error",
},
const warningLog = logger.warn("Something is not quite right, better check on it.", {
user: {
username: "someuser",
email: "[email protected]",
},
);
additional_info: {
tried_accessing: "/url/of/error",
},
});

// Example of logging errors in catch clause
function callbackThatMightFail() {
Expand Down
13 changes: 2 additions & 11 deletions packages/browser/src/browser.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
import "cross-fetch/polyfill";

import {
Context,
ILogLevel,
ILogtailLog,
ILogtailOptions,
} from "@logtail/types";
import { Context, ILogLevel, ILogtailLog, ILogtailOptions } from "@logtail/types";
import { Base } from "@logtail/core";

// Awaiting: https://bugs.chromium.org/p/chromium/issues/detail?id=571722
Expand Down Expand Up @@ -55,11 +50,7 @@ export class Browser extends Base {
* @param context: (Context) - Log context for passing structured data
* @returns Promise<ILogtailLog> after syncing
*/
public async log<TContext extends Context>(
message: string,
level?: ILogLevel,
context: TContext = {} as TContext,
) {
public async log<TContext extends Context>(message: string, level?: ILogLevel, context: TContext = {} as TContext) {
// Wrap context in an object, if it's not already
if (typeof context !== "object") {
const wrappedContext: unknown = { extra: context };
Expand Down
10 changes: 2 additions & 8 deletions packages/bunyan/src/bunyan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ export class LogtailStream extends Writable {
// Get message
// NOTE: Bunyan passes empty 'msg' when msg is missing
const use_msg_field = log.msg !== undefined && log.msg.length > 0;
const msg =
(use_msg_field ? log.msg : log.message) || "<no message provided>";
const msg = (use_msg_field ? log.msg : log.message) || "<no message provided>";

// Prevent overriding 'message' with 'msg'
// Save 'message' as 'message_field' if we are using 'msg' as message
Expand All @@ -64,12 +63,7 @@ export class LogtailStream extends Writable {
const level = getLogLevel(log.level);

// Log to Logtail
void this._logtail.log(
msg,
level,
meta,
stackContextHint as StackContextHint,
);
void this._logtail.log(msg, level, meta, stackContextHint as StackContextHint);

next();
}
Expand Down
7 changes: 1 addition & 6 deletions packages/core/src/base.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,12 +309,7 @@ describe("base class tests", () => {
return logs;
});

await Promise.all([
base.debug(message),
base.info(message),
base.warn(message),
base.error(message),
]);
await Promise.all([base.debug(message), base.info(message), base.warn(message), base.error(message)]);

// Should sync all logs in single call
expect(syncCount).toBe(1);
Expand Down
70 changes: 12 additions & 58 deletions packages/core/src/base.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,5 @@
import {
ILogLevel,
ILogtailLog,
ILogtailOptions,
Context,
LogLevel,
Middleware,
Sync,
} from "@logtail/types";
import {
makeBatch,
makeBurstProtection,
makeThrottle,
calculateJsonLogSizeBytes,
} from "@logtail/tools";
import { ILogLevel, ILogtailLog, ILogtailOptions, Context, LogLevel, Middleware, Sync } from "@logtail/types";
import { makeBatch, makeBurstProtection, makeThrottle, calculateJsonLogSizeBytes } from "@logtail/tools";
import { serializeError } from "serialize-error";

// Types
Expand Down Expand Up @@ -273,10 +260,7 @@ class Logtail {
}

// Manually serialize the log data
transformedLog = this.serialize(
transformedLog,
this._options.contextObjectMaxDepth,
);
transformedLog = this.serialize(transformedLog, this._options.contextObjectMaxDepth);

if (!this._options.sendLogsToBetterStack) {
// Return the resulting log before sending it
Expand Down Expand Up @@ -308,17 +292,8 @@ class Logtail {
return transformedLog as ILogtailLog & TContext;
}

private serialize(
value: any,
maxDepth: number,
visitedObjects: WeakSet<any> = new WeakSet(),
): any {
if (
value === null ||
typeof value === "boolean" ||
typeof value === "number" ||
typeof value === "string"
) {
private serialize(value: any, maxDepth: number, visitedObjects: WeakSet<any> = new WeakSet()): any {
if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
return value;
} else if (value instanceof Date) {
// Date instances can be invalid & toISOString() will fail
Expand All @@ -329,10 +304,7 @@ class Logtail {
return value.toISOString();
} else if (value instanceof Error) {
return serializeError(value);
} else if (
(typeof value === "object" || Array.isArray(value)) &&
(maxDepth < 1 || visitedObjects.has(value))
) {
} else if ((typeof value === "object" || Array.isArray(value)) && (maxDepth < 1 || visitedObjects.has(value))) {
if (visitedObjects.has(value)) {
if (this._options.contextObjectCircularRefWarn) {
console.warn(
Expand All @@ -349,9 +321,7 @@ class Logtail {
return `<omitted context beyond configured max depth: ${this._options.contextObjectMaxDepth}>`;
} else if (Array.isArray(value)) {
visitedObjects.add(value);
const serializedArray = value.map(item =>
this.serialize(item, maxDepth - 1, visitedObjects),
);
const serializedArray = value.map(item => this.serialize(item, maxDepth - 1, visitedObjects));
visitedObjects.delete(value);

return serializedArray;
Expand All @@ -364,11 +334,7 @@ class Logtail {
const key = item[0];
const value = item[1];

const serializedValue = this.serialize(
value,
maxDepth - 1,
visitedObjects,
);
const serializedValue = this.serialize(value, maxDepth - 1, visitedObjects);
if (serializedValue !== undefined) {
serializedObject[key] = serializedValue;
}
Expand All @@ -392,10 +358,7 @@ class Logtail {
* @param context: (Pick<ILogtailLog, "context">) - Context (optional)
* @returns Promise<ILogtailLog> after syncing
*/
public async debug<TContext extends Context>(
message: Message,
context: TContext = {} as TContext,
) {
public async debug<TContext extends Context>(message: Message, context: TContext = {} as TContext) {
return this.log(message, LogLevel.Debug, context);
}

Expand All @@ -407,10 +370,7 @@ class Logtail {
* @param context: (Pick<ILogtailLog, "context">) - Context (optional)
* @returns Promise<ILogtailLog> after syncing
*/
public async info<TContext extends Context>(
message: Message,
context: TContext = {} as TContext,
) {
public async info<TContext extends Context>(message: Message, context: TContext = {} as TContext) {
return this.log(message, LogLevel.Info, context);
}

Expand All @@ -422,10 +382,7 @@ class Logtail {
* @param context: (Pick<ILogtailLog, "context">) - Context (optional)
* @returns Promise<ILogtailLog> after syncing
*/
public async warn<TContext extends Context>(
message: Message,
context: TContext = {} as TContext,
) {
public async warn<TContext extends Context>(message: Message, context: TContext = {} as TContext) {
return this.log(message, LogLevel.Warn, context);
}

Expand All @@ -437,10 +394,7 @@ class Logtail {
* @param context: (Pick<ILogtailLog, "context">) - Context (optional)
* @returns Promise<ILogtailLog> after syncing
*/
public async error<TContext extends Context>(
message: Message,
context: TContext = {} as TContext,
) {
public async error<TContext extends Context>(message: Message, context: TContext = {} as TContext) {
return this.log(message, LogLevel.Error, context);
}

Expand Down
12 changes: 2 additions & 10 deletions packages/edge/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,7 @@ export function getStackContext(logtail: Edge): Context {
}

function getCallingFrame(logtail: Edge): StackFrame | null {
for (let fn of [
logtail.warn,
logtail.error,
logtail.info,
logtail.debug,
logtail.log,
]) {
for (let fn of [logtail.warn, logtail.error, logtail.info, logtail.debug, logtail.log]) {
const stack = stackTrace.get(fn as any);
if (stack.length > 0) return getRelevantStackFrame(stack);
}
Expand All @@ -43,9 +37,7 @@ function getCallingFrame(logtail: Edge): StackFrame | null {

function getRelevantStackFrame(frames: StackFrame[]): StackFrame {
let reversedFrames = frames.reverse();
let index = reversedFrames.findIndex(
frame => frame.getTypeName() === "EdgeWithExecutionContext",
);
let index = reversedFrames.findIndex(frame => frame.getTypeName() === "EdgeWithExecutionContext");

if (index > 0) return reversedFrames[index - 1];

Expand Down
27 changes: 5 additions & 22 deletions packages/edge/src/edge.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import { encode } from "@msgpack/msgpack";

import {
Context,
ILogLevel,
ILogtailLog,
ILogtailEdgeOptions,
LogLevel,
} from "@logtail/types";
import { Context, ILogLevel, ILogtailLog, ILogtailEdgeOptions, LogLevel } from "@logtail/types";
import { Base } from "@logtail/core";

import { ExecutionContext } from "@cloudflare/workers-types";
Expand All @@ -22,14 +16,10 @@ export class Edge extends Base {

private readonly warnAboutMissingExecutionContext: Boolean;

public constructor(
sourceToken: string,
options?: Partial<ILogtailEdgeOptions>,
) {
public constructor(sourceToken: string, options?: Partial<ILogtailEdgeOptions>) {
super(sourceToken, options);

this.warnAboutMissingExecutionContext =
options?.warnAboutMissingExecutionContext ?? true;
this.warnAboutMissingExecutionContext = options?.warnAboutMissingExecutionContext ?? true;

// Sync function
const sync = async (logs: ILogtailLog[]): Promise<ILogtailLog[]> => {
Expand Down Expand Up @@ -78,10 +68,7 @@ export class Edge extends Base {

if (ctx) {
ctx.waitUntil(log);
} else if (
this.warnAboutMissingExecutionContext &&
!this._warnedAboutMissingCtx
) {
} else if (this.warnAboutMissingExecutionContext && !this._warnedAboutMissingCtx) {
this._warnedAboutMissingCtx = true;

const warningMessage =
Expand Down Expand Up @@ -134,10 +121,6 @@ export class Edge extends Base {
private encodeAsMsgpack(logs: ILogtailLog[]): Uint8Array {
const encoded = encode(logs);

return new Uint8Array(
encoded.buffer,
encoded.byteOffset,
encoded.byteLength,
);
return new Uint8Array(encoded.buffer, encoded.byteOffset, encoded.byteLength);
}
}
21 changes: 4 additions & 17 deletions packages/koa/src/koa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,30 +36,18 @@ interface IKoaOptions {
}

const defaultKoaOpt: IKoaOptions = {
contextPaths: [
"statusCode",
"request.headers",
"request.method",
"request.length",
"request.url",
"request.query",
],
contextPaths: ["statusCode", "request.headers", "request.method", "request.length", "request.url", "request.query"],
excludedRoutes: [],
excludedMethods: [],
level: LogLevel.Info,
messageFormatter: ctx => `Koa HTTP request: ${ctx.status}`,
errorMessageFormatter: (ctx, e) =>
`Koa HTTP request error: ${(typeof e === "object" && e.message) || e}`,
errorMessageFormatter: (ctx, e) => `Koa HTTP request error: ${(typeof e === "object" && e.message) || e}`,
};

class KoaLogtail extends Logtail {
protected _koaOptions: IKoaOptions;

public constructor(
sourceToken: string,
logtailOpt?: Partial<ILogtailOptions>,
koaOpt?: Partial<IKoaOptions>,
) {
public constructor(sourceToken: string, logtailOpt?: Partial<ILogtailOptions>, koaOpt?: Partial<IKoaOptions>) {
super(sourceToken, logtailOpt);

// Set Koa-specific logging options
Expand Down Expand Up @@ -115,8 +103,7 @@ class KoaLogtail extends Logtail {
if (
!this._koaOptions.excludedMethods.includes(ctx.request.method) &&
!this._koaOptions.excludedRoutes.includes(ctx.request.url) &&
this._toLevelNumber(logLevel) >=
this._toLevelNumber(this._koaOptions.level)
this._toLevelNumber(logLevel) >= this._toLevelNumber(this._koaOptions.level)
) {
void this[logLevel](msg!, this._fromContext(ctx));
}
Expand Down
Loading

0 comments on commit aab5429

Please sign in to comment.