Skip to content

Instantly share code, notes, and snippets.

@davidgilbertson
Last active September 7, 2015 10:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidgilbertson/9821900f2203aecc7949 to your computer and use it in GitHub Desktop.
Save davidgilbertson/9821900f2203aecc7949 to your computer and use it in GitHub Desktop.
import chalk from 'chalk';
const logLevelName = process.env.LOG_LEVEL;
const isProd = process.env.NODE_ENV === 'production';
const isServer = typeof window === 'undefined';
const INFO = 20;
const WARN = 30;
const ERROR = 40;
const logLevels = {
info: INFO,
warn: WARN,
error: ERROR
};
const logLevel = logLevels[logLevelName];
if (!isServer) {
window.MAH_LOGS = [];
}
function writeToLogFile(levelName, args) {
const fs = require('fs');
const path = require('path');
const logFilePath = path.resolve(__dirname, '../../logs/log.log');
fs.writeFile(logFilePath, levelName + ':' + args);
}
export default class Logger {
constructor(namespace = '') {
this.namespace = namespace;
}
getPrefix(level, withDate) {
let result = '';
if (withDate) result += new Date().toISOString();
if (level) result += ` ${level.toUpperCase()} `;
result += this.namespace;
result += ` >`;
return result;
}
logOnClient(method = 'log', ...args) {
if (isProd) {
window.MAH_LOGS.push({
level: method,
namespace: this.namespace,
args: args
});
} else {
console[method](this.getPrefix(null, false), ...args);
}
}
logOnServer(method, ...args) {
const colors = {
info: 'gray',
warn: 'yellow',
error: 'red'
};
const color = colors[method] || 'gray';
const prefix = chalk[color](this.getPrefix(method, true));
console[method](prefix, ...args);
writeToLogFile(method, args);
}
info(...args) {
if (logLevel <= INFO) {
if (isServer) {
this.logOnServer('info', ...args);
} else {
this.logOnClient('info', ...args);
}
}
}
warn(...args) {
if (logLevel <= WARN) {
if (isServer) {
this.logOnServer('warn', ...args);
} else {
this.logOnClient('warn', ...args);
}
}
}
error(...args) {
if (logLevel <= ERROR) {
if (isServer) {
this.logOnServer('error', ...args);
} else {
this.logOnClient('error', ...args);
}
}
}
}
export default function(namespace) {
return new Logger(namespace);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment