mcopy/src/log/index.ts

71 lines
1.7 KiB
TypeScript
Raw Normal View History

2019-03-09 03:31:29 +00:00
'use strict'
import { Logger, transports } from 'winston';
import { join } from 'path';
import { mkdir, exists } from 'fs-extra';
import { homedir } from 'os';
2019-03-09 03:31:29 +00:00
const logTime = 'MM/DD/YY-HH:mm:ss'
let transport : any
/**
* Determine the location of the log file based on the operating system
* and return as an absolute string from os.homedir()
*
* @returns {string} Path to log file
**/
2019-03-09 03:31:29 +00:00
async function logFile () {
const homeDir : string = homedir();
const linuxDir : string = `/.config/mcopy/`;
const macDir : string = `/Library/Logs/mcopy/`;
const winDir : string = `/AppData/Roaming/mcopy/`;
let logPath : string = join(homeDir, linuxDir);
let dirExists : boolean;
2019-03-09 03:31:29 +00:00
if (process.platform === 'darwin') {
logPath = join(homeDir, macDir);
2019-03-09 03:31:29 +00:00
} else if (process.platform === 'win32') {
logPath = join(homeDir, winDir);
2019-03-09 03:31:29 +00:00
}
dirExists = await exists(logPath);
if (!dirExists) {
await mkdir(logPath);
2019-03-09 03:31:29 +00:00
}
return join(logPath, 'mcopy.log');
2019-03-09 03:31:29 +00:00
}
/**
* Create and return the logger transport based on settings determined in
* arguments object
*
* @param {object} arg Arguments from process
*
* @returns {object} Logger transport
**/
2019-03-09 03:31:29 +00:00
module.exports = async function (arg : any) {
let consoleFormat : any = {
colorize : true
}
let fileFormat : any = {
filename : await logFile(),
json : true
}
if (arg && arg.quiet) {
2019-03-09 03:31:29 +00:00
transport = {
info : function () { return false },
warn : function () { return false },
error : function () { return false }
2019-03-09 03:31:29 +00:00
}
} else {
if (arg && arg.label) {
consoleFormat.label = arg.label;
fileFormat.label = arg.label;
}
transport = new (Logger)({
2019-03-09 03:31:29 +00:00
transports: [
new (transports.Console)(consoleFormat),
new (transports.File)(fileFormat)
2019-03-09 03:31:29 +00:00
]
})
}
return transport
}