aboutsummaryrefslogtreecommitdiffstats
path: root/src/server/Logger.hx
blob: f089c948ac8b59f19246ab0b23a1e367db5b20b3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package server;

import haxe.Json;
import haxe.io.Path;
import sys.FileSystem;
import sys.io.File;

using Lambda;
using StringTools;

class Logger {
	final folder:String;
	final maxCount:Int;
	final verbose:Bool;
	final logs:Array<ServerEvent> = [];
	final matchFileFormat = ~/[0-9_-]+\.json$/;

	public function new(folder:String, maxCount:Int, verbose:Bool):Void {
		this.folder = folder;
		this.maxCount = maxCount;
		this.verbose = verbose;
	}

	public function log(event:ServerEvent):Void {
		logs.push(event);
		if (logs.length > 1000) logs.shift();
	}

	public function saveLog():Void {
		if (logs.length == 0) return;
		Utils.ensureDir(folder);
		removeOldestLog(folder);
		final name = DateTools.format(Date.now(), "%Y-%m-%d_%H_%M_%S");
		File.saveContent('$folder/$name.json', Json.stringify(logs, filterNulls, "\t"));
	}

	public function getLogs():Array<ServerEvent> {
		return logs;
	}

	public function filterNulls(key:Any, value:Any):Any {
		#if js
		if (value == null) return js.Lib.undefined;
		#end
		return value;
	}

	function removeOldestLog(folder:String):Void {
		final names = FileSystem.readDirectory(folder);
		if (names.count(item -> matchFileFormat.match(item)) < maxCount) return;
		var minDate = 0.0;
		var fileName:String = null;
		for (name in names) {
			final date = extractFileDate(name).getTime();
			if (minDate == 0 || minDate > date) {
				minDate = date;
				fileName = name;
			}
		}
		if (fileName == null) return;
		FileSystem.deleteFile('$folder/$fileName');
	}

	function extractFileDate(name:String):Date {
		name = Path.withoutExtension(name);
		final t = name.split("_");
		final d = t.shift().split("-");
		if (d.length != 3 && t.length != 3) return Date.fromTime(0);
		final s = '${d[0]}-${d[1]}-${d[2]} ${t[0]}:${t[1]}:${t[2]}';
		return Date.fromString(s);
	}
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage