import fs from "fs" ; import p from "path" ; import dayjs from "dayjs" ; import { app } from "electron" ; import { info , error } from "electron-log" ; export type LoggerLevel = "info" | "error" | "warn" | "success" | "notify" | "task" ; export interface LoggerType { info ( ... msg ) : void ; error ( ... msg ) : void ; warn ( ... msg ) : void ; success ( ... msg ) : void ; task ( description , handler ) : Promise < any > ; log ( level , ... msg ) : void ; } export class Logger implements LoggerType { path : string ; constructor ( private eventName ) { this . path = app . getPath ( "logs" ) ; } log ( level , ... msg ) { log ( this . path , this . eventName , level , msg ) ; } info ( ... msg ) { log ( this . path , this . eventName , "info" , msg ) ; } error ( ... msg ) { log ( this . path , this . eventName , "error" , msg ) ; } warn ( ... msg ) { log ( this . path , this . eventName , "warn" , msg ) ; } success ( ... msg ) { log ( this . path , this . eventName , "success" , msg ) ; } task ( description , handler ) { return new Promise ( async ( resolve , reject ) => { try { const t = Date . now ( ) ; log ( this . path , "system" , "task" , description ) ; resolve ( await handler ( ) ) ; log ( this . path , "system" , "task" , description + "成功,耗时:" + ( Date . now ( ) - t ) ) ; } catch ( err ) { reject ( err ) ; } } ) ; } static of ( eventName ) { return new Logger ( eventName ) ; } } export function getLogsFolderName ( ) { return new Date ( ) . toLocaleDateString ( "zh-CN" ) . split ( "/" ) . join ( "-" ) ; } export function mkdirs ( url ) { if ( ! fs . existsSync ( url ) ) { mkdirs ( p . resolve ( url , "../" ) ) ; fs . mkdirSync ( url ) ; } } param eventName param args export function log ( path , eventName , level , ... msg ) { let datetime = dayjs ( ) . format ( "YYYY-MM-DD HH:mm:ss" ) ; console . log ( `${ datetime }` , `[${ eventName }-${ level }]` , ... msg ) ; const folder = p . resolve ( p . join ( path , `/${ getLogsFolderName ( ) }/` ) ) ; const file = p . resolve ( folder , `${ eventName }.txt` ) ; try { if ( fs . existsSync ( file ) ) { fs . appendFileSync ( file , `[${ datetime }] [${ level }] : ${ msg . map ( ( m ) => m ?. toString ( ) ) . join ( " " ) } \n` ) ; } else { mkdirs ( folder ) ; fs . writeFileSync ( file , `[${ datetime }] [${ level }] :  ${ msg . map ( ( m ) => m ?. toString ( ) ) . join ( " " ) } \n` ) ; } } catch ( e ) { error ( "logger 输出错误" , e ) ; } }