Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP - fix(logger-plugin): log async completion in separate group #1269

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions packages/logger-plugin/src/action-logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import { formatTime } from './internals';
import { LogWriter } from './log-writer';

export class ActionLogger {
private synchronousWorkEnded = false;
private actionCompleted = false;
private startedTime = new Date();

constructor(private action: any, private store: Store, private logWriter: LogWriter) {}

dispatched(state: any) {
const actionName = getActionTypeFromInstance(this.action);
const formattedTime = formatTime(new Date());

const message = `action ${actionName} @ ${formattedTime}`;
const message = this.getActionLogHeader();
this.logWriter.startGroup(message);

// print payload only if at least one property is supplied
Expand All @@ -22,14 +23,40 @@ export class ActionLogger {
}

completed(nextState: any) {
if (this.synchronousWorkEnded) {
const message = `(async work completed) ${this.getActionLogHeader()}`;
this.logWriter.startGroup(message);
}
this.logWriter.logGreen('next state', nextState);
this.logWriter.endGroup();
this.actionCompleted = true;
}

errored(error: any) {
if (this.synchronousWorkEnded) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is synchronousWorkEnded?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ActionLogger instance is created when any action is dispatched. As actions can be sync and async this is a flag that basically says "oh I've completed doing my synchronous job".

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think for some reason this is all very complicated, but oh well

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need more comments I guess

const message = `(async work error) ${this.getActionLogHeader()}`;
this.logWriter.startGroup(message);
}
this.logWriter.logRedish('next state after error', this.store.snapshot());
this.logWriter.logRedish('error', error);
this.logWriter.endGroup();
this.actionCompleted = true;
}

syncWorkComplete() {
if (!this.actionCompleted) {
this.logWriter.logGreen('next state (synchronous)', this.store.snapshot());
this.logWriter.logGreen('( action doing async work... )', undefined);
this.logWriter.endGroup();
}
this.synchronousWorkEnded = true;
}

private getActionLogHeader() {
const actionName = getActionTypeFromInstance(this.action);
const formattedTime = formatTime(this.startedTime);
const message = `action ${actionName} (started @ ${formattedTime})`;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is redunant, you can

return `action ${actionName} (started @ ${formattedTime})`;

In addition, I recommend always describing the return type, since in the future you can forget to return an object instead of a returned string.

private getActionLogHeader(): string {
 
}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Will do

return message;
}

private _hasPayload(event: any) {
Expand Down
9 changes: 5 additions & 4 deletions packages/logger-plugin/src/log-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ export class LogWriter {
}

startGroup(message: string) {
const startGroupFn = this.options.collapsed
? this.logger.groupCollapsed
: this.logger.group;
try {
splincode marked this conversation as resolved.
Show resolved Hide resolved
startGroupFn.call(this.logger, message);
if (this.options.collapsed) {
this.logger.groupCollapsed(message);
} else {
this.logger.group(message);
}
} catch (e) {
console.log(message);
}
Expand Down
15 changes: 14 additions & 1 deletion packages/logger-plugin/src/logger.plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Injectable, Inject, Injector } from '@angular/core';
import { Observable, defer, empty, merge } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';

import { NgxsPlugin, NgxsNextPluginFn, Store } from '@ngxs/store';
Expand Down Expand Up @@ -27,7 +28,7 @@ export class NgxsLoggerPlugin implements NgxsPlugin {

actionLogger.dispatched(state);

return next(state, event).pipe(
const result = next(state, event).pipe(
tap(nextState => {
actionLogger.completed(nextState);
}),
Expand All @@ -36,5 +37,17 @@ export class NgxsLoggerPlugin implements NgxsPlugin {
throw error;
})
);

return afterSubscribe(result, () => actionLogger.syncWorkComplete());
}
}

function afterSubscribe<T>(source: Observable<T>, callback: VoidFunction) {
return merge(
source,
defer(() => {
callback();
return empty();
markwhitfeld marked this conversation as resolved.
Show resolved Hide resolved
})
);
}
36 changes: 28 additions & 8 deletions packages/logger-plugin/tests/helpers/logger-spy.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CallStack } from './symbols';
import { CallStack, Call } from './symbols';

/**
* Spy that mimics the required methods for custom logger implementation,
Expand Down Expand Up @@ -27,18 +27,38 @@ export class LoggerSpy {
this._callStack.push(['log', message, ...optionalParams]);
}

clear() {
this._callStack = [];
}

get callStack(): string {
const callStackWithoutTime = this._callStack.map(call => {
const callSecondParam = call[1] as string;
const callStackWithoutTime = this.getCallStack();
return LoggerSpy.createCallStack(callStackWithoutTime);
}

// remove formatted time string
if (typeof callSecondParam === 'string') {
call[1] = callSecondParam.replace(/\d{2}:\d{2}:\d{2}.\d{3}/g, '');
getCallStack(options: { excludeStyles?: boolean } = {}): any[] {
return this._callStack.map(call => {
call = removeTime(call);
if (options.excludeStyles) {
call = removeStyle(call);
}

return call;
});
}
}

return LoggerSpy.createCallStack(callStackWithoutTime);
function removeTime(item: Call): Call {
const [first, second, ...rest] = item;
if (typeof second === 'string') {
return [first, second.replace(/\d{2}:\d{2}:\d{2}.\d{3}/g, ''), ...rest];
}
return item;
}

function removeStyle(item: Call): Call {
const [first, second, , ...rest] = item;
if (typeof second === 'string' && second.startsWith('%c ')) {
return [first, second.substring(3), ...rest];
}
return item;
}
4 changes: 3 additions & 1 deletion packages/logger-plugin/tests/helpers/symbols.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export type CallStack = (string | {})[][];
export type CallParam = string | {};
export type Call = CallParam[];
export type CallStack = Call[];
Loading