From b4c45b564b1e34bb72e1fa900f21f32286047f1a Mon Sep 17 00:00:00 2001 From: Lam Wei Li Date: Wed, 30 Mar 2022 03:53:29 +0800 Subject: [PATCH] chore(fix): fileDepth for ESM --- lib/layouts.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/lib/layouts.js b/lib/layouts.js index 7bcf1e7..a762e4d 100644 --- a/lib/layouts.js +++ b/lib/layouts.js @@ -2,6 +2,7 @@ const dateFormat = require('date-format'); const os = require('os'); const util = require('util'); const path = require('path'); +const url = require('url'); const debug = require('debug')('log4js:layouts'); const styles = { @@ -250,6 +251,35 @@ function patternLayout(pattern, tokens) { function fileName(loggingEvent, specifier) { let filename = loggingEvent.fileName || ''; + + // support for ESM as it uses url instead of path for file + /* istanbul ignore next: unsure how to simulate ESM for test coverage */ + const convertFileURLToPath = function(filepath) { + const urlPrefix = 'file://'; + if (filepath.startsWith(urlPrefix)) { + // https://nodejs.org/api/url.html#urlfileurltopathurl + if (typeof url.fileURLToPath === 'function') { + filepath = url.fileURLToPath(filepath); + } + // backward-compatible for nodejs pre-10.12.0 (without url.fileURLToPath method) + else { + // posix: file:///hello/world/foo.txt -> /hello/world/foo.txt -> /hello/world/foo.txt + // win32: file:///C:/path/foo.txt -> /C:/path/foo.txt -> \C:\path\foo.txt -> C:\path\foo.txt + // win32: file://nas/foo.txt -> //nas/foo.txt -> nas\foo.txt -> \\nas\foo.txt + filepath = path.normalize(filepath.replace(new RegExp(`^${urlPrefix}`), '')); + if (process.platform === 'win32') { + if (filepath.startsWith('\\')) { + filepath = filepath.slice(1); + } else { + filepath = path.sep + path.sep + filepath; + } + } + } + } + return filepath; + }; + filename = convertFileURLToPath(filename); + if (specifier) { const fileDepth = parseInt(specifier, 10); const fileList = filename.split(path.sep);