Move logger out of Strapi.js

This commit is contained in:
Alexandre Bodin 2021-08-03 09:12:58 +02:00
parent a0011840e8
commit 10ef480bc0
12 changed files with 160 additions and 381 deletions

View File

@ -2,7 +2,7 @@ module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
admin: {
autoOpen: true,
// autoOpen: true,
auth: {
secret: env('ADMIN_JWT_SECRET', 'example-token'),
},

View File

@ -1,18 +1,15 @@
'use strict';
const http = require('http');
const path = require('path');
const fse = require('fs-extra');
const Koa = require('koa');
const Router = require('koa-router');
const _ = require('lodash');
const chalk = require('chalk');
const CLITable = require('cli-table3');
const { models, getAbsoluteAdminUrl, getAbsoluteServerUrl } = require('@strapi/utils');
const { models } = require('@strapi/utils');
const { createLogger } = require('@strapi/logger');
const { Database } = require('@strapi/database');
const loadConfiguration = require('./core/app-configuration');
const loadConfiguration = require('./core/app-configuration');
const utils = require('./utils');
const loadModules = require('./core/load-modules');
const bootstrap = require('./core/bootstrap');
@ -27,6 +24,7 @@ const createEntityService = require('./services/entity-service');
const entityValidator = require('./services/entity-validator');
const createTelemetry = require('./services/metrics');
const createUpdateNotifier = require('./utils/update-notifier');
const createStartupLogger = require('./utils/startup-logger');
const ee = require('./utils/ee');
const LIFECYCLES = {
@ -64,8 +62,7 @@ class Strapi {
// internal services.
this.fs = createStrapiFs(this);
this.eventHub = createEventHub();
this.requireProjectBootstrap();
this.startupLogger = createStartupLogger(this);
createUpdateNotifier(this).notify();
}
@ -82,78 +79,6 @@ class Strapi {
return this.requestHandler(req, res);
}
requireProjectBootstrap() {
const bootstrapPath = path.resolve(this.dir, 'config/functions/bootstrap.js');
if (fse.existsSync(bootstrapPath)) {
require(bootstrapPath);
}
}
logStats() {
const columns = Math.min(process.stderr.columns, 80) - 2;
console.log();
console.log(chalk.black.bgWhite(_.padEnd(' Project information', columns)));
console.log();
const infoTable = new CLITable({
colWidths: [20, 50],
chars: { mid: '', 'left-mid': '', 'mid-mid': '', 'right-mid': '' },
});
const isEE = strapi.EE === true && ee.isEE === true;
infoTable.push(
[chalk.blue('Time'), `${new Date()}`],
[chalk.blue('Launched in'), Date.now() - this.config.launchedAt + ' ms'],
[chalk.blue('Environment'), this.config.environment],
[chalk.blue('Process PID'), process.pid],
[chalk.blue('Version'), `${this.config.info.strapi} (node ${process.version})`],
[chalk.blue('Edition'), isEE ? 'Enterprise' : 'Community']
);
console.log(infoTable.toString());
console.log();
console.log(chalk.black.bgWhite(_.padEnd(' Actions available', columns)));
console.log();
}
logFirstStartupMessage() {
this.logStats();
console.log(chalk.bold('One more thing...'));
console.log(
chalk.grey('Create your first administrator 💻 by going to the administration panel at:')
);
console.log();
const addressTable = new CLITable();
const adminUrl = getAbsoluteAdminUrl(strapi.config);
addressTable.push([chalk.bold(adminUrl)]);
console.log(`${addressTable.toString()}`);
console.log();
}
logStartupMessage() {
this.logStats();
console.log(chalk.bold('Welcome back!'));
if (this.config.serveAdminPanel === true) {
console.log(chalk.grey('To manage your project 🚀, go to the administration panel at:'));
const adminUrl = getAbsoluteAdminUrl(strapi.config);
console.log(chalk.bold(adminUrl));
console.log();
}
console.log(chalk.grey('To access the server ⚡️, go to:'));
const serverUrl = getAbsoluteServerUrl(strapi.config);
console.log(chalk.bold(serverUrl));
console.log();
}
initServer() {
this.server = http.createServer(this.handleRequest.bind(this));
// handle port in use cleanly
@ -237,7 +162,7 @@ class Strapi {
if (err) return this.stopWithError(err);
// Is the project initialised?
const isInitialised = await utils.isInitialised(this);
const isInitialized = await utils.isInitialized(this);
// Should the startup message be displayed?
const hideStartupMessage = process.env.STRAPI_HIDE_STARTUP_MESSAGE
@ -245,10 +170,10 @@ class Strapi {
: false;
if (hideStartupMessage === false) {
if (!isInitialised) {
this.logFirstStartupMessage();
if (!isInitialized) {
this.startupLogger.logFirstStartupMessage();
} else {
this.logStartupMessage();
this.startupLogger.logStartupMessage();
}
}
@ -266,13 +191,13 @@ class Strapi {
cb();
}
// if (
// (this.config.environment === 'development' &&
// this.config.get('server.admin.autoOpen', true) !== false) ||
// !isInitialised
// ) {
// await utils.openBrowser.call(this);
// }
const shouldOpenAdmin =
this.config.environment === 'development' &&
this.config.get('server.admin.autoOpen', true) !== false;
if (shouldOpenAdmin || !isInitialized) {
await utils.openBrowser(this.config);
}
};
const listenSocket = this.config.get('server.socket');
@ -314,6 +239,14 @@ class Strapi {
process.exit(exitCode);
}
loadAdmin() {
this.admin = require('@strapi/admin/strapi-server');
// TODO: rename into just admin and ./config/admin.js
const userAdminConfig = strapi.config.get('server.admin');
this.config.set('server.admin', _.merge(this.admin.config, userAdminConfig));
}
async load() {
this.app.use(async (ctx, next) => {
if (ctx.request.url === '/_health' && ['HEAD', 'GET'].includes(ctx.request.method)) {
@ -326,11 +259,7 @@ class Strapi {
const modules = await loadModules(this);
this.admin = require('@strapi/admin/strapi-server');
// TODO: rename into just admin and ./config/admin.js
const userAdminConfig = strapi.config.get('server.admin');
this.config.set('server.admin', _.merge(this.admin.config, userAdminConfig));
this.loadAdmin();
this.api = modules.api;
this.components = modules.components;
@ -394,7 +323,6 @@ class Strapi {
await initializeHooks.call(this);
await this.runLifecyclesFunctions(LIFECYCLES.BOOTSTRAP);
await this.freeze();
this.isLoaded = true;
return this;
@ -481,14 +409,6 @@ class Strapi {
});
}
async freeze() {
Object.freeze(this.config);
Object.freeze(this.dir);
Object.freeze(this.admin);
Object.freeze(this.plugins);
Object.freeze(this.api);
}
getModel(uid) {
return this.contentTypes[uid] || this.components[uid];
}

View File

@ -16,7 +16,7 @@
<body lang="en">
<section class="wrapper">
<h1><img class="logo" src="<%= strapi.config.server.url %>/assets/images/logo_login.png" /></h1>
<% if (strapi.config.environment === 'development' && isInitialised) { %>
<% if (strapi.config.environment === 'development' && isInitialized) { %>
<div class="informations">
<div>
<span class="environment"><%= strapi.config.environment %></span>
@ -31,7 +31,7 @@
<% } %>
</div>
</div>
<% } else if (strapi.config.environment === 'development' && !isInitialised) { %>
<% } else if (strapi.config.environment === 'development' && !isInitialized) { %>
<div class="lets-started">
<h2>Let's get started!</h2>
<p>To discover the power provided by Strapi, you need to create an administrator.</p>
@ -55,7 +55,7 @@
<% } %>
</section>
<% if (strapi.config.environment === 'development' && !isInitialised) { %>
<% if (strapi.config.environment === 'development' && !isInitialized) { %>
<script>
var images=document.querySelectorAll('.people-saying-hello img');var nextIndex=0;setInterval(function(){var currentIndex=0;images.forEach(function(image,index){if(image.className==='visible'){currentIndex=index}});nextIndex=currentIndex+1;if(nextIndex===images.length){nextIndex=0}
images.forEach(function(image){image.classList.remove('visible')})

View File

@ -36,10 +36,10 @@ module.exports = strapi => {
if (ctx.body != null || ctx.status !== 404) return;
ctx.url = 'index.html';
const isInitialised = await utils.isInitialised(strapi);
const isInitialized = await utils.isInitialized(strapi);
const data = {
serverTime: new Date().toUTCString(),
isInitialised,
isInitialized,
..._.pick(strapi, [
'config.info.version',
'config.info.name',

View File

@ -1,26 +1,9 @@
'use strict';
// Dependencies.
const { isEmpty, isNil } = require('lodash');
const openBrowser = require('./openBrowser');
const openBrowser = require('./open-browser');
const isInitialized = require('./is-initialized');
module.exports = {
/*
* Return false where there is no administrator, otherwise return true.
*/
async isInitialised(strapi) {
try {
if (isEmpty(strapi.admin)) {
return true;
}
// test if there is at least one admin
const anyAdministrator = await strapi.query('strapi::user').findOne({ select: ['id'] });
return !isNil(anyAdministrator);
} catch (err) {
strapi.stopWithError(err);
}
},
isInitialized,
openBrowser,
};

View File

@ -0,0 +1,23 @@
'use strict';
const { isEmpty, isNil } = require('lodash/fp');
/**
* Test if the strapi application is considered as initialized (1st user has been created)
* @param {Strapi} strapi
* @returns {boolean}
*/
module.exports = async function isInitialized(strapi) {
try {
if (isEmpty(strapi.admin)) {
return true;
}
// test if there is at least one admin
const anyAdministrator = await strapi.query('strapi::user').findOne({ select: ['id'] });
return !isNil(anyAdministrator);
} catch (err) {
strapi.stopWithError(err);
}
};

View File

@ -0,0 +1,12 @@
'use strict';
var open = require('open');
const { getAbsoluteAdminUrl } = require('@strapi/utils');
async function openBrowser(config) {
const url = getAbsoluteAdminUrl(config);
return open(url);
}
module.exports = openBrowser;

View File

@ -1,145 +0,0 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var execSync = require('child_process').execSync;
var chalk = require('chalk');
var spawn = require('cross-spawn');
var opn = require('opn');
const fetch = require('node-fetch');
const { getAbsoluteAdminUrl } = require('@strapi/utils');
// https://github.com/sindresorhus/opn#app
var OSX_CHROME = 'google chrome';
const Actions = Object.freeze({
NONE: 0,
BROWSER: 1,
SCRIPT: 2,
});
function getBrowserEnv() {
// Attempt to honor this environment variable.
// It is specific to the operating system.
// See https://github.com/sindresorhus/opn#app for documentation.
const value = process.env.BROWSER;
let action;
if (!value) {
// Default.
action = Actions.BROWSER;
} else if (value.toLowerCase().endsWith('.js')) {
action = Actions.SCRIPT;
} else if (value.toLowerCase() === 'none') {
action = Actions.NONE;
} else {
action = Actions.BROWSER;
}
return { action, value };
}
function executeNodeScript(scriptPath, url) {
const extraArgs = process.argv.slice(2);
const child = spawn('node', [scriptPath, ...extraArgs, url], {
stdio: 'inherit',
});
child.on('close', code => {
if (code !== 0) {
console.log();
console.log(chalk.red('The script specified as BROWSER environment variable failed.'));
console.log(`${chalk.cyan(scriptPath)} exited with code ${code}.`);
console.log();
return;
}
});
return true;
}
function startBrowserProcess(browser, url) {
// If we're on OS X, the user hasn't specifically
// requested a different browser, we can try opening
// Chrome with AppleScript. This lets us reuse an
// existing tab when possible instead of creating a new one.
const shouldTryOpenChromeWithAppleScript =
process.platform === 'darwin' && (typeof browser !== 'string' || browser === OSX_CHROME);
if (shouldTryOpenChromeWithAppleScript) {
try {
// Try our best to reuse existing tab
// on OS X Google Chrome with AppleScript
execSync('ps cax | grep "Google Chrome"');
execSync(`osascript resources/openChrome.applescript "${encodeURI(url)}"`, {
cwd: __dirname,
stdio: 'ignore',
});
return true;
} catch (err) {
strapi.log.error('Failed to open Google Chrome with AppleScript');
}
}
// Another special case: on OS X, check if BROWSER has been set to "open".
// In this case, instead of passing `open` to `opn` (which won't work),
// just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
// https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768
if (process.platform === 'darwin' && browser === 'open') {
browser = undefined;
}
// Fallback to opn
// (It will always open new tab)
try {
var options = { app: browser };
opn(url, options).catch(() => {}); // Prevent `unhandledRejection` error.
return true;
} catch (err) {
return false;
}
}
async function pingDashboard(url, multipleTime = false) {
try {
await fetch(url, { method: 'HEAD', timeout: 300, body: null });
// Inform the user that we're going to open the administration panel.
this.log.info('⏳ Opening the admin panel...');
} catch (e) {
if (e.code !== 'ECONNREFUSED' && e.type !== 'request-timeout') {
return console.error(e);
}
// Only display once.
if (!multipleTime) {
this.log.warn(`⚠️ The admin panel is unavailable... Impossible to open it in the browser.`);
}
}
}
/**
* Reads the BROWSER evironment variable and decides what to do with it. Returns
* true if it opened a browser or ran a node.js script, otherwise false.
*/
async function openBrowser() {
const url = getAbsoluteAdminUrl(strapi.config);
// Ping the dashboard to ensure it's available.
await pingDashboard.call(this, url);
const { action, value } = getBrowserEnv();
switch (action) {
case Actions.NONE:
// Special case: BROWSER="none" will prevent opening completely.
return false;
case Actions.SCRIPT:
return executeNodeScript(value, url);
case Actions.BROWSER:
return startBrowserProcess(value, url);
default:
throw new Error('Not implemented.');
}
}
module.exports = openBrowser;

View File

@ -1,83 +0,0 @@
(*
Copyright (c) 2015-present, Facebook, Inc.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*)
property targetTab: null
property targetTabIndex: -1
property targetWindow: null
on run argv
set theURL to item 1 of argv
tell application "Chrome"
if (count every window) = 0 then
make new window
end if
-- 1: Looking for tab running debugger
-- then, Reload debugging tab if found
-- then return
set found to my lookupTabWithUrl(theURL)
if found then
set targetWindow's active tab index to targetTabIndex
tell targetTab to reload
tell targetWindow to activate
set index of targetWindow to 1
return
end if
-- 2: Looking for Empty tab
-- In case debugging tab was not found
-- We try to find an empty tab instead
set found to my lookupTabWithUrl("chrome://newtab/")
if found then
set targetWindow's active tab index to targetTabIndex
set URL of targetTab to theURL
tell targetWindow to activate
return
end if
-- 3: Create new tab
-- both debugging and empty tab were not found
-- make a new tab with url
tell window 1
activate
make new tab with properties {URL:theURL}
end tell
end tell
end run
-- Function:
-- Lookup tab with given url
-- if found, store tab, index, and window in properties
-- (properties were declared on top of file)
on lookupTabWithUrl(lookupUrl)
tell application "Chrome"
-- Find a tab with the given url
set found to false
set theTabIndex to -1
repeat with theWindow in every window
set theTabIndex to 0
repeat with theTab in every tab of theWindow
set theTabIndex to theTabIndex + 1
if (theTab's URL as string) contains lookupUrl then
-- assign tab, tab index, and window to properties
set targetTab to theTab
set targetTabIndex to theTabIndex
set targetWindow to theWindow
set found to true
exit repeat
end if
end repeat
if found then
exit repeat
end if
end repeat
end tell
return found
end lookupTabWithUrl

View File

@ -0,0 +1,75 @@
'use strict';
const chalk = require('chalk');
const CLITable = require('cli-table3');
const _ = require('lodash/fp');
const { getAbsoluteAdminUrl, getAbsoluteServerUrl } = require('@strapi/utils');
const ee = require('./ee');
module.exports = app => {
return {
logStats() {
const columns = Math.min(process.stderr.columns, 80) - 2;
console.log();
console.log(chalk.black.bgWhite(_.padEnd(columns, ' Project information')));
console.log();
const infoTable = new CLITable({
colWidths: [20, 50],
chars: { mid: '', 'left-mid': '', 'mid-mid': '', 'right-mid': '' },
});
const isEE = app.EE === true && ee.isEE === true;
infoTable.push(
[chalk.blue('Time'), `${new Date()}`],
[chalk.blue('Launched in'), Date.now() - app.config.launchedAt + ' ms'],
[chalk.blue('Environment'), app.config.environment],
[chalk.blue('Process PID'), process.pid],
[chalk.blue('Version'), `${app.config.info.strapi} (node ${process.version})`],
[chalk.blue('Edition'), isEE ? 'Enterprise' : 'Community']
);
console.log(infoTable.toString());
console.log();
console.log(chalk.black.bgWhite(_.padEnd(columns, ' Actions available')));
console.log();
},
logFirstStartupMessage() {
this.logStats();
console.log(chalk.bold('One more thing...'));
console.log(
chalk.grey('Create your first administrator 💻 by going to the administration panel at:')
);
console.log();
const addressTable = new CLITable();
const adminUrl = getAbsoluteAdminUrl(strapi.config);
addressTable.push([chalk.bold(adminUrl)]);
console.log(`${addressTable.toString()}`);
console.log();
},
logStartupMessage() {
this.logStats();
console.log(chalk.bold('Welcome back!'));
if (app.config.serveAdminPanel === true) {
console.log(chalk.grey('To manage your project 🚀, go to the administration panel at:'));
const adminUrl = getAbsoluteAdminUrl(strapi.config);
console.log(chalk.bold(adminUrl));
console.log();
}
console.log(chalk.grey('To access the server ⚡️, go to:'));
const serverUrl = getAbsoluteServerUrl(strapi.config);
console.log(chalk.bold(serverUrl));
console.log();
},
};
};

View File

@ -60,7 +60,7 @@
"node-fetch": "2.6.1",
"node-machine-id": "1.1.12",
"node-schedule": "1.3.2",
"opn": "^5.3.0",
"open": "8.2.1",
"ora": "^5.4.0",
"package-json": "6.5.0",
"qs": "^6.10.1",

View File

@ -5765,16 +5765,6 @@ bonjour@^3.5.0:
multicast-dns "^6.0.1"
multicast-dns-service-types "^1.1.0"
bookshelf@^1.0.1:
version "1.2.0"
resolved "https://registry.yarnpkg.com/bookshelf/-/bookshelf-1.2.0.tgz#cb972aa2316405d3a4af9cb1e2814895ab23283e"
integrity sha512-rm04YpHkLej6bkNezKUQjzuXV30rbyEHQoaKvfQ3fOyLYxPeB18uBL+h2t6SmeXjfsB+aReMmbhkMF/lUTbtMA==
dependencies:
bluebird "^3.7.2"
create-error "~0.3.1"
inflection "^1.12.0"
lodash "^4.17.15"
boolbase@^1.0.0, boolbase@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e"
@ -7297,11 +7287,6 @@ create-ecdh@^4.0.0:
bn.js "^4.1.0"
elliptic "^6.5.3"
create-error@~0.3.1:
version "0.3.1"
resolved "https://registry.yarnpkg.com/create-error/-/create-error-0.3.1.tgz#69810245a629e654432bf04377360003a5351a23"
integrity sha1-aYECRaYp5lRDK/BDdzYAA6U1GiM=
create-hash@^1.1.0, create-hash@^1.1.2, create-hash@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/create-hash/-/create-hash-1.2.0.tgz#889078af11a63756bcfb59bd221996be3a9ef196"
@ -7856,6 +7841,11 @@ defer-to-connect@^2.0.0:
resolved "https://registry.yarnpkg.com/defer-to-connect/-/defer-to-connect-2.0.1.tgz#8016bdb4143e4632b77a3449c6236277de520587"
integrity sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==
define-lazy-prop@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz#3f7ae421129bcaaac9bc74905c98a0009ec9ee7f"
integrity sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==
define-properties@^1.1.2, define-properties@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1"
@ -11213,11 +11203,6 @@ inflection@1.12.0, inflection@~1.12.0:
resolved "https://registry.yarnpkg.com/inflection/-/inflection-1.12.0.tgz#a200935656d6f5f6bc4dc7502e1aecb703228416"
integrity sha1-ogCTVlbW9fa8TcdQLhrstwMihBY=
inflection@^1.12.0:
version "1.13.1"
resolved "https://registry.yarnpkg.com/inflection/-/inflection-1.13.1.tgz#c5cadd80888a90cf84c2e96e340d7edc85d5f0cb"
integrity sha512-dldYtl2WlN0QDkIDtg8+xFwOS2Tbmp12t1cHa5/YClU6ZQjTFm7B66UcVbh9NQB+HvT5BAd2t5+yKsBkw5pcqA==
inflection@~1.3.0:
version "1.3.8"
resolved "https://registry.yarnpkg.com/inflection/-/inflection-1.3.8.tgz#cbd160da9f75b14c3cc63578d4f396784bf3014e"
@ -11596,7 +11581,7 @@ is-directory@^0.3.1:
resolved "https://registry.yarnpkg.com/is-directory/-/is-directory-0.3.1.tgz#61339b6f2475fc772fd9c9d83f5c8575dc154ae1"
integrity sha1-YTObbyR1/Hcv2cnYP1yFddwVSuE=
is-docker@2.2.1, is-docker@^2.0.0:
is-docker@2.2.1, is-docker@^2.0.0, is-docker@^2.1.1:
version "2.2.1"
resolved "https://registry.yarnpkg.com/is-docker/-/is-docker-2.2.1.tgz#33eeabe23cfe86f14bde4408a02c0cfb853acdaa"
integrity sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==
@ -15376,6 +15361,15 @@ only@~0.0.2:
resolved "https://registry.yarnpkg.com/only/-/only-0.0.2.tgz#2afde84d03e50b9a8edc444e30610a70295edfb4"
integrity sha1-Kv3oTQPlC5qO3EROMGEKcCle37Q=
open@8.2.1:
version "8.2.1"
resolved "https://registry.yarnpkg.com/open/-/open-8.2.1.tgz#82de42da0ccbf429bc12d099dad2e0975e14e8af"
integrity sha512-rXILpcQlkF/QuFez2BJDf3GsqpjGKbkUUToAIGo9A0Q6ZkoSGogZJulrUdwRkrAsoQvoZsrjCYt8+zblOk7JQQ==
dependencies:
define-lazy-prop "^2.0.0"
is-docker "^2.1.1"
is-wsl "^2.2.0"
open@^7.0.3:
version "7.4.2"
resolved "https://registry.yarnpkg.com/open/-/open-7.4.2.tgz#b8147e26dcf3e426316c730089fd71edd29c2321"