• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript winston.format类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中winston.format的典型用法代码示例。如果您正苦于以下问题:TypeScript format类的具体用法?TypeScript format怎么用?TypeScript format使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了format类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: getConfig

export function getConfig() {

  const configPath = process.env.CONFIG_PATH || process.argv[2] || './config.json'
  let config: Config
  try {
    config = Object.assign(
      {}, configDefaults, JSON.parse(fs.readFileSync(configPath).toString()))
  } catch (e) {
    console.error(`Error reading config "${configPath}": ${e}`)
    config = Object.assign({}, configDefaults)
  }

  const formats = [
    config.argsTransport.colorize ? winston.format.colorize() : null,
    config.argsTransport.timestamp ?
      winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }) : null,
    config.argsTransport.json ? winston.format.json() : winston.format.simple()
  ].filter(f => f !== null)
  const format = formats.length ? winston.format.combine(...formats) : null

  logger.configure({
    format: format, 
    transports: [new winston.transports.Console(config.argsTransport)]
  })

  return config
}
开发者ID:blockstack,项目名称:blockstack-registrar,代码行数:27,代码来源:config.ts


示例2: getConfig

export function getConfig() {
  const configPath = process.env.CONFIG_PATH || process.argv[2] || './config.json'
  let config: Config
  try {
    config = { ...configDefaults, ...JSON.parse(fs.readFileSync(configPath).toString()) }
  } catch (e) {
    console.error(`Failed to read config: ${e}`)
    config = { ...configDefaults }
  }

  if (process.env['GAIA_DISK_STORAGE_ROOT_DIR']) {
    config.diskSettings.storageRootDirectory = process.env['GAIA_DISK_STORAGE_ROOT_DIR']
  }

  const formats = [
    config.argsTransport.colorize ? winston.format.colorize() : null,
    config.argsTransport.timestamp ?
      winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }) : null,
    config.argsTransport.json ? winston.format.json() : winston.format.simple()
  ].filter(f => f !== null)
  const format = formats.length ? winston.format.combine(...formats) : null

  logger.configure({
    format: format,
    transports: [new winston.transports.Console(config.argsTransport)]
  })

  return config
}
开发者ID:blockstack,项目名称:blockstack-registrar,代码行数:29,代码来源:config.ts


示例3: createLogger

  public static createLogger(
    gatsbyEnv: GatsbyEnv = GatsbyEnv.Development,
  ): Logger {
    const logger = winston.createLogger({
      format: winston.format.json(),
      level: 'info',
      transports: [
        // ==================================================================
        // - Write to all logs with level `info` and below to `combined.log`
        // - Write all logs error (and below) to `error.log`.
        // =================================================================
        new winston.transports.File({ filename: 'error.log', level: 'error' }),
        new winston.transports.File({ filename: 'combined.log' }),
      ],
    })

    // =====================================================================
    // If we're not in production then log to the `console` with the format:
    // `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
    // =====================================================================
    if (gatsbyEnv !== GatsbyEnv.Production) {
      logger.add(
        new winston.transports.Console({
          format: winston.format.simple(),
        }),
      )
    }
    return logger
  }
开发者ID:jessestuart,项目名称:jessestuart.com,代码行数:29,代码来源:log.ts


示例4: constructor

    constructor(browser: string, headlessMode: boolean = false, logger?: winston.Logger) {

        if(logger){
            this.logger =logger;
        }else {
            this.logger = winston.loggers.get('tasteeLog');
            this.logger.configure({
                level: 'info',
                format: winston.format.combine(
                    winston.format.colorize(),
                    winston.format.splat(),
                    winston.format.simple()
                  ),
                transports: [
                    new winston.transports.Console()
                ]
              });
        }

        if (browser) {
            let webdriver = require('selenium-webdriver');
            switch (browser) {
                case 'chrome':
                    if (headlessMode) {
                        var chrome = require('selenium-webdriver/chrome');
                        this.driver = new webdriver.Builder()
                            .withCapabilities(selenium.Capabilities.chrome())
                            .setChromeOptions(new chrome.Options().headless())
                            .build();
                    }
                    else {
                        this.driver = new webdriver.Builder()
                            .forBrowser('chrome')
                            .build();
                    }
                    break;
                case 'firefox':
                    if (headlessMode) {
                        var firefox = require('selenium-webdriver/firefox');
                        this.driver = new webdriver.Builder()
                            .withCapabilities(selenium.Capabilities.firefox())
                            .setFirefoxOptions(new firefox.Options().headless())
                            .build();
                    }
                    else {
                        this.driver = new webdriver.Builder()
                            .forBrowser('firefox')
                            .build();
                    }
                    break;
                default:
                    this.driver = new webdriver.Builder()
                        .forBrowser('phantomjs')
                        .build();
                    break;
            }
        }
        this.reporter = new TasteeReporter();
    }
开发者ID:tastee,项目名称:tastee-core,代码行数:59,代码来源:tastee-engine.ts


示例5: constructor

	constructor() {
		const alignedWithColorsAndTime = winston.format.combine(
			winston.format.colorize(),
			winston.format.timestamp(),
			//winston.format.align(),
			winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`),
		);

		this.textLogger = winston.createLogger({
			format: alignedWithColorsAndTime,
			transports: [],
			level: config.vpdb.logging.level,
		});

		if (config.vpdb.logging.console.enabled) {
			this.textLogger.add(new winston.transports.Console());
		}
		/* istanbul ignore next */
		if (config.vpdb.logging.file.text) {
			const logPath = resolve(config.vpdb.logging.file.text);
			const transport = new DailyRotateFile({
				filename: basename(logPath),
				dirname: dirname(logPath),
				zippedArchive: true,
				datePattern: 'YYYY-MM',
			});
			transport.on('rotate', (oldFilename, newFilename) => {
				this.info(null, '[app] Rotating text logs from %s to %s.', oldFilename, newFilename);
			});
			transport.on('new', newFilename => {
				this.info(null, '[app] Creating new text log at %s.', newFilename);
			});
			this.textLogger.add(transport);
			this.info(null, '[app] Text logger enabled at %s.', logPath);
		}
		/* istanbul ignore next */
		if (config.vpdb.logging.file.json) {
			const logPath = resolve(config.vpdb.logging.file.json);
			const transport = new DailyRotateFile({
				filename: basename(logPath),
				dirname: dirname(logPath),
				zippedArchive: true,
				datePattern: 'YYYY-MM',
			});
			transport.on('rotate', (oldFilename, newFilename) => {
				this.info(null, '[app] Rotating JSON logs from %s to %s.', oldFilename, newFilename);
			});
			transport.on('new', newFilename => {
				this.info(null, '[app] Creating new JSON log at %s.', newFilename);
			});
			this.jsonLogger = winston.createLogger({
				format: winston.format.json(),
				transports: [transport],
				level: config.vpdb.logging.level,
			});
			this.info(null, '[app] JSON logger enabled at %s.', logPath);
		}
	}
开发者ID:freezy,项目名称:node-vpdb,代码行数:58,代码来源:logger.ts


示例6: setVerbosity

 setVerbosity (v: LoggerOptions["level"]) {
     this.logger.configure({
         level: v,
         transports: [new winston.transports.Console()],
         format: winston.format.combine(
             winston.format.colorize({ all: true }),
             logFmt
         )
     })
 }
开发者ID:0mkara,项目名称:remix,代码行数:10,代码来源:logger.ts


示例7: constructor

 constructor () {
     this.logger = winston.createLogger({
         level: 'error',
         transports: [new winston.transports.Console()],
         format: winston.format.combine(
             winston.format.colorize({ all: true }),
             logFmt
         )
     })
 }
开发者ID:0mkara,项目名称:remix,代码行数:10,代码来源:logger.ts


示例8: getColorStatus

export const formatterFunc = options => {
    // The return string will be passed to logger.
    const meta = options.meta;
    const message = options.message;
    let msg = "";

    if (meta.logSource === LogSource.HTTP_LOG_HANDLER) {
        // one-line log message
        if (meta.req) {
            msg = msg + meta.req.method + " " + meta.req.url;
            if (meta.res) {
                msg = msg + " " + getColorStatus(meta.res.statusCode) + " - " + meta.res.responseTime + " ms ";
            }
        }

        // if more details are required, display also the meta object (full req/res)
        const reqDetails = config.httpLogDetails && config.httpLogDetails.request;
        const resDetails = config.httpLogDetails && config.httpLogDetails.response;
        if (reqDetails && resDetails) {
            if (
                reqDetails.general === LogDetail.FULL ||
                (reqDetails.headers === LogDetail.PARTIAL || reqDetails.headers === LogDetail.FULL) ||
                reqDetails.body ||
                resDetails.headers ||
                resDetails.body
            ) {
                msg = msg + "\n" + JSON.stringify(meta, null, 4);
            }
        }
    } else if (meta.logSource === LogSource.ERROR_HANDLER) {
        msg = msg + (undefined !== message ? message : "");
        if (meta && Object.keys(meta).length > 0) {
            const stack = meta.stack;
            if (stack) {
                delete meta.stack;
            }
            msg = msg + "\n" + JSON.stringify(meta, null, 4);

            if (stack) {
                msg = msg + "\n" + stack;
            }
        }
    } else {
        // logSource === LogSource.CODE
        msg = msg + (undefined !== message ? message : "");
        if (meta && Object.keys(meta).length > 0) {
            const stack = meta.stack;
            if (stack) {
                delete meta.stack;
            }
            msg = msg + "\n" + JSON.stringify(meta, null, 4);

            if (stack) {
                msg = msg + "\n" + stack;
            }
        }
    }

    return format.colorize(options.level) + " " + msg;
};
开发者ID:lmaran,项目名称:scoala21,代码行数:60,代码来源:winston-console.formatter.ts


示例9: constructor

  /**
   * Constructs a new instance of PolymerLogger. This creates a new internal
   * `winston` logger, which is what we use to handle most of our logging logic.
   *
   * Should generally called with getLogger() instead of calling directly.
   */
  constructor(options: Options) {
    options = Object.assign({colorize: true}, options);

    const formats = [];
    if (options.colorize) {
      formats.push(winston.format.colorize());
    }
    formats.push(winston.format.align());
    formats.push(plylogPrettify({ colorize: options.colorize }));
    this._transport = defaultConfig.transportFactory({
      level: options.level || 'info',
      format: winston.format.combine(...formats),
    });

    this._logger = winston.createLogger({transports: [this._transport]});

    this.error = this._log.bind(this, 'error');
    this.warn = this._log.bind(this, 'warn');
    this.info = this._log.bind(this, 'info');
    this.debug = this._log.bind(this, 'debug');
  }
开发者ID:Polymer,项目名称:plylog,代码行数:27,代码来源:index.ts


示例10: default

export default ({ config }: { config: LoggerConfig }): Logger => {
  const myFormat = printf(info => {
    return `${info.timestamp} ${info.level}: ${info.message}`;
  });

  const logger = createLogger({
    level: config.level,
    format: combine(timestamp(), myFormat),
    transports: [new transports.Console({ format: format.simple() })],
  });

  return logger;
};
开发者ID:sebelga,项目名称:blog-app-googlecloud,代码行数:13,代码来源:logger.ts


示例11: function

/**
 * Configure logger
 * @param  {string} logfile Path to logfile
 * @param  {object} config Configuration for transports
 * @return {winston.Logger}
 */
export default function(app: Application, options: ILoggingOptions) {
  const cwd = process.cwd();
  const logFile = path.resolve(cwd, `${options.dir}/${options.file}`);
  const addRequestId = require("express-request-id")({ setHeader: false });

  app.use(addRequestId);
  morgan.token("id", (req: IRequestWithId) => req.id.split("-")[0]);

  app.use(morgan("[:date[iso] #:id] Started :method :url for :remote-addr", {immediate: true}));

  app.use(morgan("[: date[iso] #: id] Completed : status : res[content - length] in : response - time ms"));

  // If logs directory does not exist, create one
  if (!fs.existsSync(path.resolve(cwd, options.dir))) {
    mkdirp.sync(path.resolve(cwd, options.dir));
  }

  // If log file does not exist, create one with empty content.
  if (!fs.existsSync(logFile)) {
    fs.writeFileSync(logFile, "");
  }

  const logger = winston.createLogger({
    exitOnError: false,
    format: winston.format.json(),
    level: "info",
    transports: [
      new winston.transports.File({
        filename: logFile,
        handleExceptions: true,
        level: "info",
        maxFiles: 5,
        maxsize: 5242880, // 5MB
      }),
      new winston.transports.Console({
        handleExceptions: true,
        level: "debug",
      }),
    ],

  });

  return logger;
}
开发者ID:charlesponti,项目名称:cthulhu,代码行数:50,代码来源:logger.ts


示例12:

import * as winston from 'winston';

/**
 * A default logger for the app
 */
export const logger = winston.createLogger({
    format: winston.format.json(),
    level: 'info',
    transports: [
        new winston.transports.File({ filename: 'error.log', level: 'error' }),
        new winston.transports.Console({
            format: winston.format.simple(),
        }),
    ],
});
开发者ID:sahilkabra,项目名称:expense-manager,代码行数:15,代码来源:logger.ts


示例13:

import * as winston from 'winston';

export const Logger: winston.Logger =
  winston.createLogger({
                         transports:  [
                           new winston.transports.File({
                                                         filename: 'logs/error.log',
                                                         level:    'error',
                                                         maxFiles: 5,
                                                         maxsize:  10485760,
                                                         format:   winston.format.json(),
                                                       }),
                           new winston.transports.File({
                                                         filename: 'logs/all.log',
                                                         maxFiles: 5,
                                                         maxsize:  10485760,
                                                         format:   winston.format.json(),
                                                       }),
                           new winston.transports.Console({
                                                            level:            'debug',
                                                            handleExceptions: true,
                                                            format:           winston.format.combine(
                                                              winston.format.colorize(),
                                                              winston.format.simple(),
                                                            ),
                                                          }),
                         ],
                         exitOnError: false,
                       });
开发者ID:trungx,项目名称:vue-starter,代码行数:29,代码来源:Logger.ts


示例14: createLogger

import { configure, format, transports } from 'winston';

const { combine, timestamp, splat } = format;

const myFormat = format.printf(info => {
  return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`;
});

export interface LoggerOptions {
  readonly logType: string;
  readonly logFile: string;
  readonly logLevel: string;
}

export function createLogger(options: LoggerOptions): void {
  const { logType, logLevel } = options;

  configure({
    exitOnError: false,
    format: combine(
      timestamp({
        format: 'YYYY-MM-DD HH:mm:ss'
      }),
      splat(),
      myFormat
    ),
    level: logLevel,
    transports:
      logType === 'file'
        ? [
            new transports.File({
开发者ID:mshick,项目名称:arrivals-osx,代码行数:31,代码来源:logger.ts


示例15:

      filename: magic8bot.loggerFile,
      datePattern: 'YYYY-MM-DD-HH',
      maxSize: '20m',
      maxFiles: '7d',
    })
  }

  if (process.env.NODE_ENV === 'development' || !fileLogger) {
    yield new winston.transports.Console({
      format: formatter,
    })
  }
}

const textFormat = winston.format.printf((info) => {
  return `${info.timestamp} [${info.level.padStart(5, ' ')}]: ${info.message}`
})

// prettier-ignore
const formatter = winston.format.combine(
    winston.format.timestamp(),
    winston.format.splat(),
    winston.format.simple(),
    textFormat
)

const isFileLoggerAvailable = () => {
  return magic8bot.loggerFile && magic8bot.loggerFile.length > 0
}

export const logger = winston.createLogger({
开发者ID:magic8bot,项目名称:magic8bot,代码行数:31,代码来源:logger.ts


示例16:

import winston from 'winston';

export const logger = {
  level: 'error',
  exitOnError: false,
  transports: [ new winston.transports.Console({ format: winston.format.simple() }) ],
};
开发者ID:RWOverdijk,项目名称:stix,代码行数:7,代码来源:logger.ts


示例17: createLogger

const { combine, timestamp, label, printf, colorize } = format;

const logger = createLogger({
  format:
    process.env.NODE_ENV === 'development'
      ? combine(
          colorize({ all: true }),
          label({ label: 'Wetty' }),
          timestamp(),
          printf(
            info =>
              `${info.timestamp} [${info.label}] ${info.level}: ${info.message}`
          )
        )
      : format.json(),
  transports: [
    new transports.Console({
      level: process.env.NODE_ENV === 'development' ? 'debug' : 'info',
      handleExceptions: true,
    }),
  ],
});

logger.stream = {
  write(message: string): void {
    logger.info(message);
  },
};

export default logger;
开发者ID:krishnasrinivas,项目名称:wetty,代码行数:30,代码来源:logger.ts


示例18: describe

describe('Tastee Engine', function () {
    let engine: TasteeEngine;

    logger.configure({
        level: 'debug',
        format: winston.format.combine(
            winston.format.colorize(),
            winston.format.splat(),
            winston.format.simple()
          ),
        transports: [
            new winston.transports.Console()
        ]
      });

    beforeEach(function () {
        engine = new TasteeEngine(null);
        let driver = jasmine.createSpyObj("driver", ["quit"]);
        engine.driver = driver;
    });

    it(" propagates logger", function () {
        const infoLog = winston.loggers.get('infoLog');
        infoLog.configure({
            level: 'info'
          });

        let engineInfo = new TasteeEngine(null, false, infoLog);
        expect(engineInfo.logger).toBe(infoLog);
    });

    it(" quits selenium driver properly", function () {
        engine.stop();
        expect(engine.driver.quit).toHaveBeenCalled();
    });

    it(" execute simple js code", (done) => {
        let instruction = new Instruction(1, 'a line', '1+1');

        let promise = engine.execute([instruction]);
        promise.then(result => {
            expect(result.length).toBe(1);
            expect(result[0].valid).toBe(true);
            done();
        });
    });

    it(" execute empty codeLines", (done) => {
        let instruction = new Instruction(1, 'a line', '');

        engine.execute([instruction]).then(result => {
            expect(result.length).toBe(1);
            expect(result[0].valid).toBe(true);
            done();
        });
    });

    it(" execute unknown instruction", (done) => {
        let instruction = new Instruction(1, 'a line', 'bad code line');

        engine.execute([instruction]).then(result => {
            expect(result.length).toBe(1);
            expect(result[0].valid).toBe(false);
            done();
        });
    });

    it(" execute promise error", (done) => {
        let instruction = new Instruction(1, 'a line', 'throw new Error("exception!");');

        engine.execute([instruction]).then(result => {
            expect(result.length).toBe(1);
            expect(result[0].valid).toBe(false);
            done();
        });
    });
});
开发者ID:tastee,项目名称:tastee-core,代码行数:77,代码来源:tastee-engine.spec.ts


示例19: keysExcluder

const excludedKeys = {
  level: true,
  message: true,
  splat: true,
  timestamp: true,
  label: true
}
function keysExcluder (key, value) {
  return excludedKeys[key] === true ? undefined : value
}

const loggerFormat = winston.format.printf((info) => {
  let additionalInfos = JSON.stringify(info, keysExcluder, 2)
  if (additionalInfos === '{}') additionalInfos = ''
  else additionalInfos = ' ' + additionalInfos

  return `[${info.label}] ${toTimeFormat(info.timestamp)} ${info.level}: ${info.message}${additionalInfos}`
})

const logger = new winston.createLogger({
  transports: [
    new winston.transports.Console({
      level: program['level'] || 'debug',
      stderrLevels: [],
      format: winston.format.combine(
        winston.format.splat(),
        labelFormatter,
        winston.format.colorize(),
        loggerFormat
      )
开发者ID:jiang263,项目名称:PeerTube,代码行数:30,代码来源:parse-log.ts


示例20: createLogger

export const Logger = (options: LoggerOptions) => {

    options = _.defaultsDeep(options || {}, {
        fluentD: {},
        logDirectory: null,
        format: {
            timestamp: true,
            json: false,
            colorize: false
        },
        cwd: process.cwd()
    });

    // Defining custom formats 
    const styleFormats = [];

    // special case: if json is not defined , use by default the custom format 
    if (options.format.json === false) {
        // going to global
        styleFormats.push( loggerFormat);
    }
    else{
        styleFormats.push(format.json());
    }
    // TODO: enable dynamic formats and parameters , for  now it is only using basic types with no parameters    
    _.forEach(['colorize', 'timestamp'], (value) => {
        if (_.get(options.format, `${value}`) === true) {
            styleFormats.push(format[`${value}`]());
        }
    });
    const _logger = createLogger({
        format: format.combine(...styleFormats)
    });
    // Adding a new Console transport
    _logger.add(new transports.Console());
    if (options.logDirectory) {
        // Create the log directory if it doesn't exist
        mkdirSync(options.logDirectory);

        _logger.add(new transports.File({
            filename: path.resolve(options.logDirectory, 'app.log'),
            maxFiles: 5,
            maxsize: 10485760,
            level: 'info'
        }));
    }
    // Adding fluentD transport
    if (!_.isEmpty(options.fluentD)) {
        let name: string = getPackageName(getPackageManifest(options.cwd));

        options = _.defaultsDeep(options, {
            fluentD: {
                host: 'localhost',
                port: 24224,
                timeout: 3.0,
                tag: name || 'labshare'
            }
        });

        _logger.add(new FluentTransport(options.fluentD.tag, options.fluentD));
    }
    // Workaround to support the Morgan request logging middleware
    return _.assign(_logger, {
        stream: () => {
            let self: any = this;
            return {
                write(options?: any): void {
                    self.info(options);
                }
            }
        }
    });;

}
开发者ID:LabShare,项目名称:lsc,代码行数:74,代码来源:logger.ts



注:本文中的winston.format类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript winston.loggers类代码示例发布时间:2022-05-25
下一篇:
TypeScript winston.LoggerInstance类代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap