Skip to content

Commit

Permalink
Merge pull request #6 from FullStacksDev/logging
Browse files Browse the repository at this point in the history
Lightweight logging
  • Loading branch information
jits authored Feb 12, 2024
2 parents 0bf3104 + d704504 commit 1a1e998
Show file tree
Hide file tree
Showing 19 changed files with 81 additions and 29 deletions.
3 changes: 2 additions & 1 deletion app/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
{
"ignoreRestSiblings": true
}
]
],
"no-console": ["error"]
}
},
{
Expand Down
8 changes: 7 additions & 1 deletion app/angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,13 @@
"stylePreprocessorOptions": {
"includePaths": ["src/styles"]
},
"scripts": []
"scripts": [],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.test.ts"
}
]
}
},
"lint": {
Expand Down
1 change: 1 addition & 0 deletions app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@angular/ssr": "^17.1.3",
"@ngrx/operators": "^17.1.0",
"@ngrx/signals": "^17.1.0",
"consola": "^3.2.3",
"express": "^4.18.2",
"firebase": "^10.8.0",
"ngxtension": "^2.0.0",
Expand Down
8 changes: 8 additions & 0 deletions app/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions app/server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr';
import { consola } from 'consola';
import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import bootstrap from './src/main.server';

// The Express app is exported so that it can be used by serverless Functions.
Expand Down Expand Up @@ -52,7 +53,7 @@ function run(): void {
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
consola.log(`Node Express server listening on http://localhost:${port}`);
});
}

Expand Down
5 changes: 4 additions & 1 deletion app/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import { Component, inject } from '@angular/core';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { RouterOutlet } from '@angular/router';
import { SwUpdate, VersionReadyEvent } from '@angular/service-worker';
import { createLogger } from '@app-shared/logger';
import { RuntimeService } from '@app-shared/runtime.service';
import { filter } from 'rxjs';

const logger = createLogger('AppComponent');

@Component({
selector: 'app-root',
standalone: true,
Expand All @@ -23,7 +26,7 @@ export class AppComponent {
this.informUserOfUpdate();
});

console.log('*** this.#runtimeService.isServer = ', this.#runtimeService.isServer);
logger.log('this.#runtimeService.isServer =', this.#runtimeService.isServer);
}
private informUserOfUpdate(): void {
this.#snackBar
Expand Down
5 changes: 4 additions & 1 deletion app/src/app/login/data/login.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Injectable } from '@angular/core';
import { injectAuth } from '@app-shared/firebase/auth';
import { createLogger } from '@app-shared/logger';
import {
ActionCodeSettings,
AuthError,
Expand All @@ -8,6 +9,8 @@ import {
signInWithEmailLink,
} from 'firebase/auth';

const logger = createLogger('LoginService');

@Injectable({
providedIn: 'root',
})
Expand Down Expand Up @@ -45,7 +48,7 @@ export class LoginService {
}

private handleFirebaseError(error: AuthError): string {
console.log(error);
logger.error('Firebase Auth error:', error);

let message = 'Unknown error';

Expand Down
2 changes: 1 addition & 1 deletion app/src/app/login/feature/login-flow.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { signal } from '@angular/core';
import { MockBuilder, MockInstance, MockRender } from 'ng-mocks';
import { buildRxMethodSpy } from '../../../testing/helpers';
import { buildRxMethodSpy } from '../../../test/helpers/ngrx';
import { LoginFlowComponent } from './login-flow.component';
import { LoginFlowStore } from './login-flow.store';

Expand Down
11 changes: 6 additions & 5 deletions app/src/app/login/feature/login-flow.store.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable, effect, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthStore } from '@app-shared/auth/data/auth.store';
import { createLogger } from '@app-shared/logger';
import { tapResponse } from '@ngrx/operators';
import {
getState,
Expand Down Expand Up @@ -49,6 +50,8 @@ const initialState: LoginFlowState = {
error: null,
};

const logger = createLogger('LoginFlowStore');

const _LoginFlowStore = signalStore(
withState<LoginFlowState>(initialState),
withComputed(() => {
Expand Down Expand Up @@ -91,9 +94,7 @@ const _LoginFlowStore = signalStore(
return {
triggerLoginLink: rxMethod<{ email: string }>(
pipe(
tap((params) =>
console.log(`[LoginFlowStore] #triggerLoginLink - email = ${params.email}`),
),
tap((params) => logger.log(`#triggerLoginLink - email = ${params.email}`)),
tap(() => setProcessing()),
exhaustMap(({ email }) => {
return from(loginService.triggerLoginLink(email, document.location.href)).pipe(
Expand All @@ -117,7 +118,7 @@ const _LoginFlowStore = signalStore(
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
handleLoginLinkIfAvailable: rxMethod<void>(
pipe(
tap(() => console.log('[LoginFlowStore] #handleLoginLinkIfAvailable')),
tap(() => logger.log('#handleLoginLinkIfAvailable')),
map(() => document.location.href),
filter((url) => loginService.isLoginLink(url)),
tap(() => setProcessing()),
Expand Down Expand Up @@ -159,7 +160,7 @@ const _LoginFlowStore = signalStore(
}),
withHooks({
onInit(store) {
effect(() => console.log('[LoginPageStore] State:', getState(store)));
effect(() => logger.log('State:', getState(store)));

// Listen for changes to the user and trigger completion once we have one.
effect(
Expand Down
9 changes: 5 additions & 4 deletions app/src/app/shared/auth/data/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { inject, Injectable } from '@angular/core';
import { injectAuth, user$ } from '@app-shared/firebase/auth';
import { createLogger } from '@app-shared/logger';
import { RuntimeService } from '@app-shared/runtime.service';
import { User } from '@common';
import { map, Observable, of, tap } from 'rxjs';

const logger = createLogger('AuthService');

@Injectable({
providedIn: 'root',
})
Expand All @@ -12,9 +15,7 @@ export class AuthService {
readonly #auth = injectAuth();

readonly #firebaseUser$: Observable<User | null> = user$(this.#auth).pipe(
tap((firebaseUser) =>
console.log('[AuthService] Received auth user data from Firebase:', firebaseUser),
),
tap((firebaseUser) => logger.log('Received auth user data from Firebase:', firebaseUser)),
map((firebaseUser) => {
if (firebaseUser) {
return {
Expand All @@ -31,7 +32,7 @@ export class AuthService {
}),
);

readonly #nullUser$ = of(null).pipe(tap(() => console.log('[AuthService] null user set')));
readonly #nullUser$ = of(null).pipe(tap(() => logger.log('null user set')));

readonly user$: Observable<User | null> = this.#runtimeService.isServer
? this.#nullUser$
Expand Down
11 changes: 7 additions & 4 deletions app/src/app/shared/auth/data/auth.store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Injectable, computed, effect, inject } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { createLogger } from '@app-shared/logger';
import { User } from '@common';
import { tapResponse } from '@ngrx/operators';
import {
Expand Down Expand Up @@ -47,6 +48,8 @@ const initialState: AuthState = {
error: null,
};

const logger = createLogger('AuthStore');

const _AuthStore = signalStore(
{ providedIn: 'root' },
withState<AuthState>(initialState),
Expand Down Expand Up @@ -86,7 +89,7 @@ const _AuthStore = signalStore(
tapResponse({
next: (user) => setConnected(user),
error: (error) => {
console.error('[AuthStore] Error getting auth data:', error);
logger.error('Error getting auth data:', error);
setError('Failed to fetch auth info');
},
}),
Expand All @@ -102,7 +105,7 @@ const _AuthStore = signalStore(
return {
manageStream: rxMethod<'connect' | 'disconnect'>(
pipe(
tap((action) => console.log(`[AuthStore] #manageStream - action = ${action}`)),
tap((action) => logger.log(`#manageStream - action = ${action}`)),
tap((action) => (action === 'connect' ? setConnecting() : null)),
switchMap((action) =>
action === 'connect' ? connectedStream$() : disconnectedStream$(),
Expand All @@ -113,7 +116,7 @@ const _AuthStore = signalStore(
}),
withHooks({
onInit(store) {
effect(() => console.log('[AuthStore] State:', getState(store)));
effect(() => logger.log('State:', getState(store)));

store.manageStream('connect');
},
Expand All @@ -123,7 +126,7 @@ const _AuthStore = signalStore(
@Injectable({ providedIn: 'root' })
export class AuthStore extends _AuthStore {
readonly waitUntilConnected$ = toObservable(this.status).pipe(
tap((status) => console.log('[AuthStore] waitUntilConnected - status =', status)),
tap((status) => logger.log('waitUntilConnected - status =', status)),
filter((status) => status === 'connected'),
shareReplay(1),
);
Expand Down
13 changes: 7 additions & 6 deletions app/src/app/shared/auth/util/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { inject } from '@angular/core';
import { CanMatchFn, Route, Router } from '@angular/router';
import { createLogger } from '@app-shared/logger';
import { RuntimeService } from '@app-shared/runtime.service';
import { map, take } from 'rxjs';
import { AuthStore } from '../data/auth.store';

const logger = createLogger('authGuard');

export function authGuard(allowOnly: 'authed' | 'not-authed'): CanMatchFn {
console.log(`[authGuard] Factory called - allowOnly = ${allowOnly}`);
logger.log(`Factory called - allowOnly = ${allowOnly}`);

return (route: Route) => {
const runtimeService = inject(RuntimeService);
const router = inject(Router);

console.log(
`[authGuard] Factory called - allowOnly = ${allowOnly}, route.path = ${route.path}`,
);
logger.log(`Factory called - allowOnly = ${allowOnly}, route.path = ${route.path}`);

if (runtimeService.isServer) {
console.log('[authGuard] Server side - render the /loader view instead');
logger.log('Server side - render the /loader view instead');
return router.createUrlTree(['/loader']);
}

Expand All @@ -26,7 +27,7 @@ export function authGuard(allowOnly: 'authed' | 'not-authed'): CanMatchFn {
map(() => {
const isAuthenticated = authStore.isAuthenticated();

console.log(`[authGuard] After auth connected - isAuthenticated = ${isAuthenticated}`);
logger.log(`After auth connected - isAuthenticated = ${isAuthenticated}`);

switch (allowOnly) {
case 'authed':
Expand Down
3 changes: 2 additions & 1 deletion app/src/app/shared/firebase/functions.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { DEFAULT_FIREBASE_REGION } from '@common';
import { consola } from 'consola';
import { Auth } from 'firebase/auth';
import { connectFunctionsEmulator, getFunctions } from 'firebase/functions';
import { createInjectionToken } from 'ngxtension/create-injection-token';
import { environment } from '../../../environments/environment';
import { FIREBASE_AUTH } from './auth';

console.log('DEFAULT_FIREBASE_REGION = ', DEFAULT_FIREBASE_REGION);
consola.log('DEFAULT_FIREBASE_REGION = ', DEFAULT_FIREBASE_REGION);

// eslint-disable-next-line @typescript-eslint/no-unused-vars
function functionsFactory(_: Auth) {
Expand Down
6 changes: 6 additions & 0 deletions app/src/app/shared/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { consola } from 'consola';
import { environment } from '../../environments/environment';

consola.level = environment.logLevel;

export const createLogger = (tag: string) => consola.withTag(tag);
1 change: 1 addition & 0 deletions app/src/environments/environment.live.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export const environment = {
useEmulators: false,
logLevel: 0, // See https://unjs.io/packages/consola#log-level
firebaseConfig: {
apiKey: 'AIzaSyAlU3Zb-MVoSEbtyQF9iE-8sMbtO5g8KHk',
authDomain: 'angular-and-firebase-template.firebaseapp.com',
Expand Down
13 changes: 13 additions & 0 deletions app/src/environments/environment.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export const environment = {
useEmulators: true,
logLevel: Number.NEGATIVE_INFINITY, // See https://unjs.io/packages/consola#log-level
firebaseConfig: {
apiKey: 'this-is-a-demo-project',
authDomain: 'this-is-a-demo-project',
databaseURL: 'https://demo-test.europe-west1.firebasedatabase.app',
projectId: 'demo-test',
storageBucket: 'this-is-a-demo-project',
messagingSenderId: 'this-is-a-demo-project',
appId: 'this-is-a-demo-project',
},
};
1 change: 1 addition & 0 deletions app/src/environments/environment.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export const environment = {
useEmulators: true,
logLevel: 5, // See https://unjs.io/packages/consola#log-level
firebaseConfig: {
apiKey: 'this-is-a-demo-project',
authDomain: 'this-is-a-demo-project',
Expand Down
5 changes: 3 additions & 2 deletions app/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { consola } from 'consola';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';

bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));
bootstrapApplication(AppComponent, appConfig).catch((err) => consola.error(err));
File renamed without changes.

0 comments on commit 1a1e998

Please sign in to comment.