import { createWriteStream , renameSync , statSync , WriteStream } from 'fs' ; import * as _ from 'lodash' ; import moment from 'moment' ; import { EOL } from 'os' ; import { findLogFileName } from 'root/app/log-rotate/find_log_file_name' ; let file ; let stream ; let date ; export function transportFile ( msg , appName , maxSize ) { const text = msg ; date = dateDetermination ( date ) ; if ( ! stream ) { file = file !== undefined ? file : findLogFileName ( appName , date ) ; if ( maxSize > 0 ) { logRotate ( file , maxSize ) ; } stream = createWriteStream ( file , { flags : 'a' } ) as WriteStream | undefined ; } if ( ! stream ) { return false ; } stream . write ( [ text , EOL ] . join ( '' ) ) ; return true ; } function dateDetermination ( d ) { const now = getNowDate ( ) ; if ( d !== now ) { stream = undefined ; file = undefined ; } return now ; } function logRotate ( _file , maxSize ) { try { const stat = statSync ( _file ) ; if ( stat . size > maxSize ) { renameSync ( _file , _file . replace ( /log$/ , `${ Math . random ( ) . toString ( ) . substr ( 2 , 5 ) }.log` ) ) ; } } catch ( e ) { } } function getNowDate ( ) { return `${ moment ( ) . get ( 'year' ) }-${ _ . padStart ( ( moment ( ) . get ( 'month' ) + 1 ) . toString ( ) , 2 , '0' ) }-${ _ . padStart ( moment ( ) . get ( 'date' ) . toString ( ) , 2 , '0' ) }` ; }