Skip to content

Instantly share code, notes, and snippets.

@alexsunxl
Created July 2, 2019 04:40
Show Gist options
  • Save alexsunxl/fbec6e7d7611bcbf7c752ff05251bb62 to your computer and use it in GitHub Desktop.
Save alexsunxl/fbec6e7d7611bcbf7c752ff05251bb62 to your computer and use it in GitHub Desktop.
winstonjs logger show caller line number
const winston = require('winston')
const { combine, timestamp, label, printf } = winston.format;
const moment = require('moment')
const path = require('path')
const PROJECT_ROOT = path.join(__dirname, '..')
const myFormat = printf(info => {
const ds = moment(info.timestamp).format('YYYY-MM-DD HH:mm:ss')
return `[${ds}] [${info.level}] ${info.message}`
})
function createLogger(file_name) {
// 按日期切割日志文件
const day = moment().format('YYYY-MM-DD')
const file = path.resolve(
__dirname,
'./log',
`${file_name}_${day}.log`,
)
const logger = winston.createLogger({
level: 'info',
format: combine(
timestamp(),
myFormat
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: file })
]
})
function generate(func, call) {
return function() {
func.apply(call, formatLogArguments(arguments))
}
}
logger.info = generate(logger.info, logger)
logger.warn = generate(logger.warn, logger)
logger.error = generate(logger.error, logger)
return logger
}
/**
* Attempts to add file and line number info to the given log arguments.
*/
function formatLogArguments (args) {
args = Array.prototype.slice.call(args)
var stackInfo = getStackInfo(1)
if (stackInfo) {
// get file path relative to project root
var calleeStr = '[' + stackInfo.relativePath + ':' + stackInfo.line + ']'
if (typeof (args[0]) === 'string') {
args[0] = calleeStr + ' ' + args[0]
} else {
args.unshift(calleeStr)
}
}
return args
}
/**
* Parses and returns info about the call stack at the given index.
*/
function getStackInfo (stackIndex) {
// get call stack, and analyze it
// get all file, method, and line numbers
var stacklist = (new Error()).stack.split('\n').slice(3)
// stack trace format:
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
// do not remove the regex expresses to outside of this method (due to a BUG in node.js)
var stackReg = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi
var stackReg2 = /at\s+()(.*):(\d*):(\d*)/gi
var s = stacklist[stackIndex] || stacklist[0]
var sp = stackReg.exec(s) || stackReg2.exec(s)
if (sp && sp.length === 5) {
return {
method: sp[1],
relativePath: path.relative(PROJECT_ROOT, sp[2]),
line: sp[3],
pos: sp[4],
file: path.basename(sp[2]),
stack: stacklist.join('\n')
}
}
}
const { createLogger } = require('./logger')
const logger = createLogger('weixin')
logger.info('test') // => [2019-07-02 12:15:38] [info] [util\test.js:6] test
logger.info('test2') // => [2019-07-02 12:15:38] [info] [util\test.js:7] test2
logger.info('test3') // => [2019-07-02 12:15:38] [info] [util\test.js:8] test3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment