1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-27 10:32:58 +02:00
joplin/ReactNativeClient/lib/Logger.ts

228 lines
5.7 KiB
TypeScript
Raw Normal View History

const moment = require('moment');
const { time } = require('lib/time-utils.js');
const { FsDriverDummy } = require('lib/fs-driver-dummy.js');
2017-06-23 23:32:24 +02:00
export enum TargetType {
Database = 'database',
File = 'file',
Console = 'console',
}
enum LogLevel {
None = 0,
Error = 10,
Warn = 20,
Info = 30,
Debug = 40,
}
interface Target {
type: TargetType,
level?: LogLevel,
database?: any,
console?: any,
prefix?: string,
path?: string,
source?: string,
}
2017-06-23 23:32:24 +02:00
class Logger {
// For backward compatibility
public static LEVEL_NONE = LogLevel.None;
public static LEVEL_ERROR = LogLevel.Error;
public static LEVEL_WARN = LogLevel.Warn;
public static LEVEL_INFO = LogLevel.Info;
public static LEVEL_DEBUG = LogLevel.Debug;
public static fsDriver_:any = null;
private targets_:Target[] = [];
private level_:LogLevel = LogLevel.Info;
private lastDbCleanup_:number = time.unixMs();
2017-06-23 23:32:24 +02:00
2017-07-05 23:52:31 +02:00
static fsDriver() {
if (!Logger.fsDriver_) Logger.fsDriver_ = new FsDriverDummy();
return Logger.fsDriver_;
}
setLevel(level:LogLevel) {
2017-06-23 23:32:24 +02:00
this.level_ = level;
}
level() {
return this.level_;
}
targets() {
return this.targets_;
}
addTarget(type:TargetType, options:any = null) {
const target = { type: type };
for (const n in options) {
2017-06-23 23:32:24 +02:00
if (!options.hasOwnProperty(n)) continue;
(target as any)[n] = options[n];
2017-06-23 23:32:24 +02:00
}
this.targets_.push(target);
}
objectToString(object:any) {
2017-07-06 21:48:17 +02:00
let output = '';
if (typeof object === 'object') {
if (object instanceof Error) {
object = object as any;
2017-07-06 21:48:17 +02:00
output = object.toString();
2019-09-19 23:51:18 +02:00
if (object.code) output += `\nCode: ${object.code}`;
if (object.headers) output += `\nHeader: ${JSON.stringify(object.headers)}`;
if (object.request) output += `\nRequest: ${object.request.substr ? object.request.substr(0, 1024) : ''}`;
if (object.stack) output += `\n${object.stack}`;
2017-07-06 21:48:17 +02:00
} else {
output = JSON.stringify(object);
}
} else {
output = object;
}
2019-07-29 15:43:53 +02:00
return output;
2017-07-07 19:19:24 +02:00
}
objectsToString(...object:any[]) {
const output = [];
2017-07-07 19:19:24 +02:00
for (let i = 0; i < object.length; i++) {
2019-09-19 23:51:18 +02:00
output.push(`"${this.objectToString(object[i])}"`);
2017-07-07 19:19:24 +02:00
}
return output.join(', ');
2017-07-06 21:48:17 +02:00
}
static databaseCreateTableSql() {
const output = `
2017-07-07 19:19:24 +02:00
CREATE TABLE IF NOT EXISTS logs (
2017-07-06 21:48:17 +02:00
id INTEGER PRIMARY KEY,
source TEXT,
level INT NOT NULL,
message TEXT NOT NULL,
\`timestamp\` INT NOT NULL
);
`;
2019-07-29 15:43:53 +02:00
return output.split('\n').join(' ');
2017-07-06 21:48:17 +02:00
}
2017-07-07 19:19:24 +02:00
// Only for database at the moment
async lastEntries(limit:number = 100, options:any = null) {
if (options === null) options = {};
if (!options.levels) options.levels = [LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error];
if (!options.levels.length) return [];
2017-07-07 19:19:24 +02:00
for (let i = 0; i < this.targets_.length; i++) {
const target = this.targets_[i];
if (target.type == 'database') {
2019-09-19 23:51:18 +02:00
let sql = `SELECT * FROM logs WHERE level IN (${options.levels.join(',')}) ORDER BY timestamp DESC`;
if (limit !== null) sql += ` LIMIT ${limit}`;
return await target.database.selectAll(sql);
2017-07-07 19:19:24 +02:00
}
}
return [];
}
targetLevel(target:Target) {
if ('level' in target) return target.level;
2019-07-29 15:43:53 +02:00
return this.level();
}
log(level:LogLevel, ...object:any[]) {
if (!this.targets_.length) return;
2017-06-23 23:32:24 +02:00
Desktop: Resolves #176: Added experimental WYSIWYG editor (#2556) * Trying to get TuiEditor to work * Tests with TinyMCE * Fixed build * Improved asset loading * Added support for Joplin source blocks * Added support for Joplin source blocks * Better integration * Make sure noteDidUpdate event is always dispatched at the right time * Minor tweaks * Fixed tests * Add support for checkboxes * Minor refactoring * Added support for file attachments * Add support for fenced code blocks * Fix new line issue on code block * Added support for Fountain scripts * Refactoring * Better handling of saving and loading notes * Fix saving and loading ntoes * Handle multi-note selection and fixed new note creation issue * Fixed newline issue in test * Fixed newline issue in test * Improve saving and loading * Improve saving and loading note * Removed undeeded prop * Fixed issue when new note being saved is incorrectly reloaded * Refactoring and improve saving of note when unmounting component * Fixed TypeScript error * Small changes * Improved further handling of saving and loading notes * Handle provisional notes and fixed various saving and loading bugs * Adding back support for HTML notes * Added support for HTML notes * Better handling of editable nodes * Preserve image HTML tag when the size is set * Handle switching between editor when the note has note finished saving * Handle templates * Handle templates * Handle loading note that is being saved * Handle note being reloaded via sync * Clean up * Clean up and improved logging * Fixed TS error * Fixed a few issues * Fixed test * Logging * Various improvements * Add blockquote support * Moved CWD operation to shim * Removed deleted files * Added support for Joplin commands
2020-03-10 01:24:57 +02:00
const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
const line = `${timestamp}: `;
2017-07-07 19:19:24 +02:00
2017-06-23 23:32:24 +02:00
for (let i = 0; i < this.targets_.length; i++) {
const target = this.targets_[i];
2019-07-29 15:43:53 +02:00
if (this.targetLevel(target) < level) continue;
2017-07-06 21:48:17 +02:00
if (target.type == 'console') {
let fn = 'log';
if (level == LogLevel.Error) fn = 'error';
if (level == LogLevel.Warn) fn = 'warn';
if (level == LogLevel.Info) fn = 'info';
const consoleObj = target.console ? target.console : console;
let items = [moment().format('HH:mm:ss')];
if (target.prefix) {
items.push(target.prefix);
}
items = items.concat(...object);
Desktop: Resolves #176: Added experimental WYSIWYG editor (#2556) * Trying to get TuiEditor to work * Tests with TinyMCE * Fixed build * Improved asset loading * Added support for Joplin source blocks * Added support for Joplin source blocks * Better integration * Make sure noteDidUpdate event is always dispatched at the right time * Minor tweaks * Fixed tests * Add support for checkboxes * Minor refactoring * Added support for file attachments * Add support for fenced code blocks * Fix new line issue on code block * Added support for Fountain scripts * Refactoring * Better handling of saving and loading notes * Fix saving and loading ntoes * Handle multi-note selection and fixed new note creation issue * Fixed newline issue in test * Fixed newline issue in test * Improve saving and loading * Improve saving and loading note * Removed undeeded prop * Fixed issue when new note being saved is incorrectly reloaded * Refactoring and improve saving of note when unmounting component * Fixed TypeScript error * Small changes * Improved further handling of saving and loading notes * Handle provisional notes and fixed various saving and loading bugs * Adding back support for HTML notes * Added support for HTML notes * Better handling of editable nodes * Preserve image HTML tag when the size is set * Handle switching between editor when the note has note finished saving * Handle templates * Handle templates * Handle loading note that is being saved * Handle note being reloaded via sync * Clean up * Clean up and improved logging * Fixed TS error * Fixed a few issues * Fixed test * Logging * Various improvements * Add blockquote support * Moved CWD operation to shim * Removed deleted files * Added support for Joplin commands
2020-03-10 01:24:57 +02:00
consoleObj[fn](...items);
2017-07-06 21:48:17 +02:00
} else if (target.type == 'file') {
const serializedObject = this.objectsToString(...object);
try {
Logger.fsDriver().appendFileSync(target.path, `${line + serializedObject}\n`);
} catch (error) {
console.error('Cannot write to log file:', error);
}
2017-07-06 21:48:17 +02:00
} else if (target.type == 'database') {
const msg = this.objectsToString(...object);
2017-07-16 18:20:25 +02:00
const queries = [
2019-07-29 15:43:53 +02:00
{
sql: 'INSERT INTO logs (`source`, `level`, `message`, `timestamp`) VALUES (?, ?, ?, ?)',
params: [target.source, level, msg, time.unixMs()],
},
];
2017-07-16 18:20:25 +02:00
const now = time.unixMs();
if (now - this.lastDbCleanup_ > 1000 * 60 * 60) {
this.lastDbCleanup_ = now;
const dayKeep = 14;
queries.push({
sql: 'DELETE FROM logs WHERE `timestamp` < ?',
params: [now - 1000 * 60 * 60 * 24 * dayKeep],
});
}
target.database.transactionExecBatch(queries);
2017-06-23 23:32:24 +02:00
}
}
}
error(...object:any[]) {
return this.log(LogLevel.Error, ...object);
2019-07-29 15:43:53 +02:00
}
warn(...object:any[]) {
return this.log(LogLevel.Warn, ...object);
2019-07-29 15:43:53 +02:00
}
info(...object:any[]) {
return this.log(LogLevel.Info, ...object);
2019-07-29 15:43:53 +02:00
}
debug(...object:any[]) {
return this.log(LogLevel.Debug, ...object);
2019-07-29 15:43:53 +02:00
}
2017-06-23 23:32:24 +02:00
static levelStringToId(s:string) {
if (s == 'none') return LogLevel.None;
if (s == 'error') return LogLevel.Error;
if (s == 'warn') return LogLevel.Warn;
if (s == 'info') return LogLevel.Info;
if (s == 'debug') return LogLevel.Debug;
throw new Error(`Unknown log level: ${s}`);
2017-08-20 22:11:32 +02:00
}
static levelIdToString(id:LogLevel) {
if (id == LogLevel.None) return 'none';
if (id == LogLevel.Error) return 'error';
if (id == LogLevel.Warn) return 'warn';
if (id == LogLevel.Info) return 'info';
if (id == LogLevel.Debug) return 'debug';
throw new Error(`Unknown level ID: ${id}`);
2017-08-20 22:11:32 +02:00
}
static levelIds() {
return [LogLevel.None, LogLevel.Error, LogLevel.Warn, LogLevel.Info, LogLevel.Debug];
2017-08-20 22:11:32 +02:00
}
2017-06-23 23:32:24 +02:00
}
export default Logger;