개발/javascript
javascript console.log 내용 저장하기
LukeHan1128
2023. 7. 19. 20:00
반응형
const fs = require('fs');
const readline = require('readline');
// date and time
function getToday(){
let date_ob = new Date();
let year = date_ob.getFullYear();
let month = ('0'+(date_ob.getMonth() + 1)).slice(-2);
let date = ('0'+date_ob.getDate()).slice(-2);
return year + '-' + month + '-' + date;
}
function getTime(){
let date_ob = new Date();
let hours = ('0'+date_ob.getHours()).slice(-2);
let minutes = ('0'+date_ob.getMinutes()).slice(-2);
let seconds = ('0'+date_ob.getSeconds()).slice(-2);
return hours + ':' + minutes + ':' + seconds;
}
function getTimeMilli(){
return getTime() + '.' + new Date().getMilliseconds();
}
// logger
function fntLogger(level, data, option, setText){
let fd = fs.openSync('logs/js_'+getToday()+'.log', 'a');
try{
data = '['+getToday()+' '+getTimeMilli()+'] ['+level+'] ' + data;
fs.appendFileSync(fd, data + (undefined != option && null != option ? ' '+option.getInnerHTML() : '') + '\n', 'utf8');
if(null == setText) console.log(data, option);
else console.log('%c' + data, setText, option);
}catch(err){
}finally{
if(fd !== undefined) fs.closeSync(fd);
}
}
var logger = {
debug: function(data, option){
if(true == isDev) fntLogger('debug', data, option);
}
, info: function(data, option){
fntLogger('info', data, option);
}
, warn: function(data, option){
fntLogger('warn', data, option, 'color:orange; font-weight:bold; font-size: 13px;');
}
, error: function(data, option){
fntLogger('error', data, option, 'color:red; font-weight:bold; font-size: 15px;');
}
, fatal: function(data, option){
fntLogger('fatal', data, option, 'color:red; font-weight:bold; font-size: 18px;');
}
}
logger.debug('[debug]');
logger.info('[info]');
logger.warn('[warn]');
logger.error('[error]');
logger.fatal('[fatal]');
javascript 만 사용하여 구현하기는 어려워 node 를 사용하여 구현함
반응형