sails.config.log
Sails 應用程式中 記錄器 的設定。當您在應用程式碼中呼叫 sails.log.debug()
或 sails.log.error()
等函式,以及 Sails 自動將訊息記錄到主控台時,這些設定都會適用。此處的選項通常在 config/log.js 設定檔中指定。
屬性 | 類型 | 預設值 | 詳細資訊 |
---|---|---|---|
level | 'info' |
設定應用程式日誌中顯示的詳細程度。 | |
inspect | true |
設定為 false 以停用 captain's log 的日誌處理,日誌將改為傳遞到已設定的自訂記錄器。 | |
custom | undefined |
指定對自訂記錄器實例的參考 (例如 Winston)。如果提供,則不會直接記錄到主控台,而是會呼叫自訂記錄器公開的函式,並且會傳遞來自 Sails 的日誌訊息。如需更多資訊,請參閱 captains-log。 |
有時設定自訂記錄器很有用,特別是為了法規遵循和組織需求(例如,如果您的公司在其他應用程式中使用特定的記錄器)。在 Sails 的環境中,設定自訂記錄器也允許您攔截框架自動建立的所有日誌訊息,這對於設定關於錯誤和警告的電子郵件通知非常方便。
如果您想要這些通知,不一定必須使用自訂記錄器!事實上,通常有更直接的方法來實作自動化的 Slack、簡訊或電子郵件錯誤通知等功能。一種方法是自訂應用程式的預設伺服器錯誤回應 (
responses/serverError.js
)。另一個常見的選擇是使用像 Papertrail 這樣的產品,或是像 AppDynamics 或 NewRelic 這樣的監控服務。
以下範例示範如何設定 Winston 作為自訂記錄器,定義主控台傳輸和檔案傳輸。首先,將 winston
新增為專案的依賴項
npm install winston
然後,將 config/log.js
的內容替換為以下內容
// config/log.js
const { version } = require('../package');
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, colorize, label, printf, align } = format;
const { SPLAT } = require('triple-beam');
const { isObject } = require('lodash');
function formatObject(param) {
if (isObject(param)) {
return JSON.stringify(param);
}
return param;
}
// Ignore log messages if they have { private: true }
const all = format((info) => {
const splat = info[SPLAT] || [];
const message = formatObject(info.message);
const rest = splat.map(formatObject).join(' ');
info.message = `${message} ${rest}`;
return info;
});
const customLogger = createLogger({
format: combine(
all(),
label({ label: version }),
timestamp(),
colorize(),
align(),
printf(info => `${info.timestamp} [${info.label}] ${info.level}: ${formatObject(info.message)}`)
),
transports: [new transports.Console()]
});
module.exports.log = {
custom: customLogger,
inspect: false
// level: 'info'
};