nodejs 使用winston记录日志(打印文件名和行号)

/**
 * Created by prgma42 on 2022/9/16.
 */
const { createLogger, format, transports } = require('winston');
const fs = require('fs');
const path = require('path');
const dateUtil = require('./date_util');
const env = process.env.NODE_ENV || 'development';
const logDir = 'logs/'+dateUtil.getDateByType('YYYYMMDD');
const PROJECT_ROOT = path.join(__dirname, '..')
// Create the log directory if it does not exist
if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir);
}
const filename = path.join(logDir, 'results.log');


const logger = createLogger({
    level: env === 'production' ? 'info' : 'debug',
    format: format.combine(
        format.label({ label: path.basename(process.mainModule.filename) }),
        format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' })
    ),
    transports: [
        new transports.Console({
            format: format.combine(
                format.colorize(),
                format.printf(
                    info =>
                        `${info.timestamp} ${info.level}  ${info.message}`
                )
            )
        }),
        new transports.File({
            filename,
            format: format.combine(
                format.printf(
                    info =>
                        `${info.timestamp} ${info.level}  ${info.message}`
                )
            )
        }),
        new transports.File({
            name:'error_file',
            filename:path.join(logDir,'error.log'),
            level:'error',
            format: format.combine(
                format.printf(
                    info =>
                        `${info.timestamp} ${info.level}  ${info.message}`
                )
            )
        })
    ]
});

//module.exports = logger;

module.exports.debug = module.exports.log = function () {
    logger.debug.apply(logger, formatLogArguments(arguments))
}

module.exports.info = function () {
    logger.info.apply(logger, formatLogArguments(arguments))
}

module.exports.warn = function () {
    logger.warn.apply(logger, formatLogArguments(arguments))
}

module.exports.error = function () {
    logger.error.apply(logger, formatLogArguments(arguments))
}

//module.exports.stream = logger.stream

/**
 * Attempts to add file and line number info to the given log arguments.
 */
function formatLogArguments (args) {
    args = Array.prototype.slice.call(args)

    const stackInfo = getStackInfo(1)
    if (stackInfo) {
        // get file path relative to project root
        const calleeStr = '[' + stackInfo.relativePath + ':' + stackInfo.line + '] '
        let content = '';
        for(var i in args){
           
if (args[i]  instanceof Object) {
    content = content + ' ' + JSON.stringify(args[i]);
}else{
    content = content + ' ' + args[i]
}
        }
        if (content && content.length>0) {
            args[0] = calleeStr + ' ' + content
        } 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')
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 如果在使用Node.js的FTP模块拉取文件列表时,遇到中文文件名乱码的问题,可以使用iconv-lite模块进行编码转换,将文件名从服务器的编码转换为UTF-8编码,例如: ```javascript const ftp = require('ftp'); const iconv = require('iconv-lite'); const client = new ftp(); client.on('ready', () => { client.list((err, list) => { if (err) throw err; list.forEach((file) => { console.log(iconv.decode(file.name, 'gbk')); // 将gbk编码转换为UTF-8编码 }); client.end(); }); }); client.connect({ host: 'ftp.example.com', user: 'username', password: 'password', port: 21, encoding: 'binary' // 设置为二进制模式,避免数据传输时被转换为其他编码 }); ``` 这样就可以正确地输出中文文件名了。 ### 回答2: 在Node.js中,使用FTP拉取文件列表时,如果文件名是中文的话可能会出现乱码的问题。解决这个问题可以考虑以下几种方法: 1. 设置编码:在进行FTP操作之前,可以设置FTP连接的编码方式为UTF-8。可以通过使用iconv-lite模块来进行编码的转换,将获取到的文件名进行解码转换成正确的中文字符。 2. 文件名转码:如果FTP服务器使用的是非UTF-8编码方式,可以尝试将获取到的文件名转换成正确的编码方式。可以使用iconv-lite模块来进行转码操作。 3. 使用ftp-syst命令:在进行FTP登录后,可以尝试发送一个ftp-syst命令来获取FTP服务器使用的编码方式,然后根据返回的结果进行相应的设置和转码操作。 4. 使用FTP软件自带的命令行工具:可以考虑使用FTP服务器自带的命令行工具来进行文件列表的拉取。在命令行工具中一般不会出现中文乱码的问题。 需要注意的是,在使用以上方法解决中文乱码问题时,需要确认FTP服务器和客户端的编码方式一致,这样才能正确地进行解码和转码操作。另外,也要确保使用的模块和工具版本是最新的,以避免已知的编码问题。 ### 回答3: 在Node.js使用FTP拉取文件列表时,可能会遇到中文文件名乱码的问题。这是因为FTP服务器默认编码为ASCII,而中文文件名是以UTF-8编码存储的。为了解决乱码问题,可以按照以下步骤操作: 1. 设置使用UTF-8编码:在使用FTP连接库时,需要设置编码为UTF-8,以确保正确解析中文文件名。例如,在使用`ftp`模块时,可以通过设置`encoding`选项为`'utf8'`来指定编码格式: ```javascript const ftp = require('ftp'); const client = new ftp(); client.encoding = 'utf8'; ``` 2. 解析中文文件名:当拉取文件列表后,需要对返回的文件名进行相应的解析,以确保正确显示中文字符。一种常用的解析方法是使用`iconv-lite`库将文件名从服务器编码转换为UTF-8编码,再进行显示。例如: ```javascript const iconv = require('iconv-lite'); let fileName = iconv.decode(fileRawName, 'GB2312'); console.log(fileName); ``` 其中,`fileRawName`是从FTP服务器获取到的原始文件名,`GB2312`是FTP服务器的编码。 3. 设置FTP服务器编码:如果以上方法无法解决中文文件名乱码问题,可以尝试设置FTP服务器编码为UTF-8。具体设置方法可能因FTP服务器类型而异,可以在FTP服务器的配置文件中找到相应的选项进行设置。 总之,通过设置正确的编码格式、解析中文文件名以及尝试调整FTP服务器编码,可以解决Node.js使用FTP拉取文件列表时中文文件名乱码的问题。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值