Skip to content

Commit

Permalink
Move logging to centralized module
Browse files Browse the repository at this point in the history
  • Loading branch information
Matsuuu committed Nov 17, 2023
1 parent deac239 commit 43cbf99
Show file tree
Hide file tree
Showing 7 changed files with 30 additions and 19 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"command": ["${node_bin}", "${server_path}", "--stdio"],
"selector": "source.js, source.jsx, source.ts, source.tsx"
"selector": "text.html, source.js"
}

Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export async function analyzeLocalProject(basePath: string): Promise<AnalyzerOut
normalizeManifest(basePath, manifest);

const savePath = cacheCurrentCEM(basePath, manifest);
console.log("Manifest file written to ", savePath);
Logger.log({ message: `Manifest file written to ${savePath}`, level: LogLevel.WARN });

return {
manifest,
Expand Down
8 changes: 5 additions & 3 deletions lib/custom-elements-languageserver-core/src/cem/cem-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { JavaScriptModule } from "custom-elements-manifest";
import { addReferenceToModule, JavaScriptModuleWithRef } from "./cem-helpers.js";
import tss from "typescript/lib/tsserverlibrary.js";

Check warning on line 6 in lib/custom-elements-languageserver-core/src/cem/cem-cache.ts

View workflow job for this annotation

GitHub Actions / Qodana for JS

Unused import

Unused import tss from "typescript/lib/tsserverlibrary.js";
import { CEMUpdatedEvent, LanguageServerEventHost } from "../export.js";
import { Logger, LogLevel } from "../logger/logger.js";

export class CEMCollection {
public id: number = Date.now() + Math.floor(Math.random() * 999);
Expand All @@ -18,7 +19,7 @@ export class CEMCollection {
}

private async initializeCEMs() {
console.log("Initializing CEM's");
Logger.log({ message: "Initializing CEM's", level: LogLevel.INFO });
const dependencyPackages = getDependencyPackagesWithCEMs(this.basePath + "/node_modules");

const cemData = await CEMInstance.fromLocalPath(this.basePath);
Expand All @@ -31,7 +32,8 @@ export class CEMCollection {
this._cems = dependencyCems.filter(cemIsNotUndefined);

this.refresh(); // Initialize modules

Check notice on line 34 in lib/custom-elements-languageserver-core/src/cem/cem-cache.ts

View workflow job for this annotation

GitHub Actions / Qodana for JS

Missing await for an async function call

Missing await for an async function call
console.log(`CEM Cache initialized. LocalCEM Present: ${this._localCEM !== undefined}. Dependency CEM Count: ${dependencyCems.length}`);

Logger.log({ message: `CEM Cache initialized. LocalCEM Present: ${this._localCEM !== undefined}. Dependency CEM Count: ${dependencyCems.length}`, level: LogLevel.INFO });
}

public get modules(): Array<JavaScriptModule> {
Expand Down Expand Up @@ -106,7 +108,7 @@ function setToCEMCache(projectBasePath: string, cemCollection: CEMCollection) {
export function refreshCEMData(projectBasePath: string) {
const existingCollection = getCEMFromCacheByPath(projectBasePath);
if (!existingCollection) {
console.warn("Tried to refresh a non-existant cache. Attempted " + projectBasePath + ", but the only ones available are: ", [...CEM_COLLECTION_CACHE.keys()]);
Logger.log({ message: `Tried to refresh a non-existant cache. Attempted ${projectBasePath}, but the only ones available are: ${[...CEM_COLLECTION_CACHE.keys()]}`, level: LogLevel.WARN });
return;
}
existingCollection?.refreshLocal();

Check notice on line 114 in lib/custom-elements-languageserver-core/src/cem/cem-cache.ts

View workflow job for this annotation

GitHub Actions / Qodana for JS

Result of method call returning a promise is ignored

Promise returned from refreshLocal is ignored
Expand Down
12 changes: 9 additions & 3 deletions lib/custom-elements-languageserver-core/src/logger/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import fs from "fs";
const DEBUG = true;

export enum LogLevel {
INFO = 1,
OFF = 0,
ERROR = 1,
WARN = 2,
ERROR = 3
INFO = 3,
DEBUG = 4
}

export interface LogMessage {
Expand All @@ -15,7 +17,7 @@ export interface LogMessage {

export class Logger {
private static _instance: Logger;
private level: LogLevel = LogLevel.INFO;
private level: LogLevel = LogLevel.OFF;

public static getInstance(): Logger {
if (!Logger._instance) {
Expand All @@ -24,6 +26,10 @@ export class Logger {
return Logger._instance;
}

public static log(message: LogMessage) {
this.getInstance().log(message);

Check notice on line 30 in lib/custom-elements-languageserver-core/src/logger/logger.ts

View workflow job for this annotation

GitHub Actions / Qodana for JS

Result of method call returning a promise is ignored

Promise returned from log is ignored
}

public async log(message: LogMessage) {
// This function is set as async so that it doesn't block execution
if (message.level < this.level) {
Expand Down
17 changes: 9 additions & 8 deletions lib/server/src/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import fs from "fs";
import path from "path";
import url from "url";
import { refreshLanguageServiceForFile } from "./language-services/language-services";
import { Logger, LogLevel } from "custom-elements-languageserver-core/src/logger/logger";

// @ts-ignore
export let connection = createConnection(ProposedFeatures.all);

export function initConnection() {
console.log("Initializing connection");
Logger.log({ message: "Initializing connection", level: LogLevel.DEBUG });
// @ts-ignore
connection = createConnection(ProposedFeatures.all);

Expand Down Expand Up @@ -81,7 +82,7 @@ function onInitialize(params: InitializeParams) {
}

function onInitialized() {
console.log("Connection initialized");
Logger.log({ message: "Connection initialized", level: LogLevel.DEBUG });
if (hasConfigurationCapability) {
// Register for all configuration changes.
connection.client.register(DidChangeConfigurationNotification.type, undefined);
Expand Down Expand Up @@ -110,12 +111,12 @@ interface PackageJsonLike {
}

async function initializeProjectsInWorkSpaceFolders(workspaceFolders: WorkspaceFolder[]) {
console.log("Initializing workspaces.");
Logger.log({ message: "Initializing workspaces.", level: LogLevel.DEBUG });
workspaceFolders?.forEach(workSpaceFolder => {
console.log("Initializing workspace " + workSpaceFolder.name + " @ " + decodeURI(workSpaceFolder.uri));
Logger.log({ message: "Initializing workspace " + workSpaceFolder.name + " @ " + decodeURI(workSpaceFolder.uri), level: LogLevel.DEBUG });
let fileName = url.fileURLToPath(workSpaceFolder.uri);
const packageJsonPath = path.resolve(fileName, "package.json");
console.log("Package JSON path ", packageJsonPath);
Logger.log({ message: "Package JSON path " + packageJsonPath, level: LogLevel.DEBUG });
if (fs.existsSync(packageJsonPath)) {
try {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")) as PackageJsonLike;
Expand All @@ -124,13 +125,13 @@ async function initializeProjectsInWorkSpaceFolders(workspaceFolders: WorkspaceF
const mainFilePath = path.resolve(fileName, mainFileName);
refreshLanguageServiceForFile(mainFilePath, undefined);
} else {
console.warn("Could not find a main or module file");
Logger.log({ message: "Could not find a main or module file", level: LogLevel.WARN });
}
} catch (ex) {
console.warn("Couldn't open project " + fileName, ex);
Logger.log({ message: "Couldn't open project " + fileName + "\n" + ex, level: LogLevel.WARN });
}
} else {
console.warn("Did not find package.json for project");
Logger.log({ message: "Did not find package.json for project", level: LogLevel.WARN });
}
})
}
Expand Down
5 changes: 3 additions & 2 deletions lib/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import {
DidChangeTextDocumentParams,
} from "vscode-languageserver";

console.log("NODE VERSION: ", process.version);
console.log("Startup at ", new Date());
Logger.log({ message: "NODE VERSION: " + process.version, level: LogLevel.INFO });
Logger.log({ message: "Startup at " + new Date(), level: LogLevel.INFO });

import { TextDocument } from "vscode-languageserver-textdocument";
import { documents } from "./text-documents.js";
Expand All @@ -16,6 +16,7 @@ import { completionsHandler } from "./handlers/completions.js";
import { codeActionHandler } from "./handlers/code-actions.js";
import { codeActionResolveHandler } from "./handlers/code-action-resolve.js";
import { hoverHandler } from "./handlers/hover.js";
import { LogLevel, Logger } from "custom-elements-languageserver-core/src/logger/logger.js";

initConnection();

Expand Down
3 changes: 2 additions & 1 deletion lib/server/src/text-documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { runDiagnostics } from "./diagnostics.js";
import { connection } from "./connection.js";
import { textDocumentDataToUsableDataFromUri, UsableTextDocumentData } from "./transformers.js";
import { refreshCEMData } from "custom-elements-languageserver-core";
import { Logger, LogLevel } from "custom-elements-languageserver-core/src/logger/logger.js";

export const documentSettings = new Map<string, LanguageServerSettings>();
export let documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument);
Expand All @@ -22,7 +23,7 @@ function refreshCEM(usableData: UsableTextDocumentData) {
}

export function initDocuments() {
console.log("Initializing documents");
Logger.log({ message: "Initializing documents", level: LogLevel.DEBUG });
documents = new TextDocuments(TextDocument);
// Only keep settings for open documents
documents.listen(connection);
Expand Down

0 comments on commit 43cbf99

Please sign in to comment.