logger.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * @Author HonorLee (dev@honorlee.me)
  3. * @Version 1.0 (2018-05-04)
  4. * @License MIT
  5. */
  6. require('colors');
  7. import Tracer = require('tracer');
  8. const TracerInstance = Tracer.dailyfile({root:SYSTEM.PATH.Log,format : `{{timestamp}} | {{file}}:{{line}} {{message}}`, dateformat : "HH:MM:ss.L"});
  9. enum Level{
  10. LOG,
  11. INFO,
  12. DEBUG,
  13. WARN,
  14. ERROR
  15. }
  16. class Logger{
  17. public print(level:Level,msg:any,color:string|null):void{
  18. // console.log(new Error('test').stack)
  19. const str = `[${SYSTEM.ID}][${Level[level]}][${Moment().format('HH:mm:ss')}] ${msg}`;
  20. if(color){
  21. console.log(str[color as any]);
  22. }else{
  23. console.log(str);
  24. }
  25. const WriteLevel = SYSTEM.CONFIG.Log_Level.toUpperCase();
  26. if(Level[WriteLevel]){
  27. const wlevel = <any>Level[WriteLevel] as number;
  28. if(level >= wlevel){
  29. this.write(level,msg)
  30. }
  31. }
  32. }
  33. public write(level:Level,msg:any):void{
  34. const fun:string = Level[level].toLowerCase();
  35. TracerInstance[fun](msg);
  36. }
  37. }
  38. const LoggerInstance = new Logger();
  39. const LoggerBridge = new Proxy(LoggerInstance,{
  40. get(target:Logger,key:string){
  41. let level:Level = -1;
  42. let color:string|null = null;
  43. switch(key){
  44. case 'log':
  45. level = Level.LOG;
  46. break;
  47. case 'info':
  48. level = Level.INFO;
  49. color = 'green';
  50. break;
  51. case 'debug':
  52. level = Level.DEBUG;
  53. color = 'magenta';
  54. break;
  55. case 'warn':
  56. level = Level.WARN;
  57. color = 'yellow';
  58. break;
  59. case 'error':
  60. level = Level.ERROR;
  61. color = 'red';
  62. break;
  63. default:
  64. return null;
  65. }
  66. return function(msg:string):void{
  67. LoggerInstance.print(level,msg,color);
  68. }
  69. }
  70. })
  71. module.exports = LoggerBridge;