91 lines
2.7 KiB
JavaScript
91 lines
2.7 KiB
JavaScript
const InstanceManager = require("../utils/instanceMgr").default;
|
|
const winston = require("winston");
|
|
const WinstonCloudWatch = require("winston-cloudwatch");
|
|
const { isString, isEmpty } = require("lodash");
|
|
|
|
const createLogger = () => {
|
|
try {
|
|
const region = InstanceManager({
|
|
imex: "ca-central-1",
|
|
rome: "us-east-2"
|
|
});
|
|
|
|
const isLocal = isString(process.env?.LOCALSTACK_HOSTNAME) && !isEmpty(process.env?.LOCALSTACK_HOSTNAME);
|
|
|
|
const logGroupName = isLocal ? "development" : process.env.CLOUDWATCH_LOG_GROUP;
|
|
|
|
const winstonCloudwatchTransportDefaults = {
|
|
logGroupName: logGroupName,
|
|
awsOptions: {
|
|
region
|
|
},
|
|
jsonMessage: true
|
|
};
|
|
|
|
if (isLocal) {
|
|
winstonCloudwatchTransportDefaults.awsOptions.endpoint = `http://${process.env.LOCALSTACK_HOSTNAME}:4566`;
|
|
console.log(
|
|
`Winston Transports set to LocalStack end point: ${winstonCloudwatchTransportDefaults.awsOptions.endpoint}`
|
|
);
|
|
}
|
|
|
|
const getDevelopmentTransports = () => [
|
|
new winston.transports.Console({
|
|
level: "silly",
|
|
format: winston.format.combine(
|
|
winston.format.colorize(),
|
|
winston.format.timestamp(),
|
|
winston.format.printf(({ level, message, timestamp, user, record, object }) => {
|
|
return `${timestamp} [${level}]: ${message} ${
|
|
user ? `| user: ${JSON.stringify(user)}` : ""
|
|
} ${record ? `| record: ${JSON.stringify(record)}` : ""} ${
|
|
object ? `| object: ${JSON.stringify(object, null, 2)}` : ""
|
|
}`;
|
|
})
|
|
)
|
|
})
|
|
];
|
|
|
|
const getProductionTransports = () => [
|
|
new WinstonCloudWatch({
|
|
level: "error",
|
|
logStreamName: "errors",
|
|
...winstonCloudwatchTransportDefaults
|
|
}),
|
|
new WinstonCloudWatch({
|
|
level: "warn",
|
|
logStreamName: "warn",
|
|
...winstonCloudwatchTransportDefaults
|
|
}),
|
|
new WinstonCloudWatch({
|
|
level: "debug",
|
|
logStreamName: "debug",
|
|
...winstonCloudwatchTransportDefaults
|
|
})
|
|
];
|
|
|
|
const winstonLogger = winston.createLogger({
|
|
format: winston.format.json(),
|
|
transports:
|
|
process.env.NODE_ENV === "production"
|
|
? getProductionTransports()
|
|
: [...getDevelopmentTransports(), ...getProductionTransports()]
|
|
});
|
|
|
|
return (message, type, user, record, object) => {
|
|
winstonLogger.log({
|
|
level: type.toLowerCase(),
|
|
message: message,
|
|
user: user,
|
|
record: record,
|
|
meta: object
|
|
});
|
|
};
|
|
} catch (e) {
|
|
console.error("Logger setup failed", e);
|
|
return () => {}; // Return a no-op function in case of failure
|
|
}
|
|
};
|
|
|
|
module.exports = { log: createLogger() };
|