aboutsummaryrefslogtreecommitdiffstats
path: root/src/server/Logger.hx
blob: 42d382d38bfa133f97badc00183f53e6c37208cc (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
73
74
75
76
77
78
package server;

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

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();
		if (hasSameLatestEvents(GetTime, 5)) {
			logs.splice(logs.length - 3, 1);
		}
	}

	function hasSameLatestEvents(type:WsEventType, count:Int):Bool {
		if (logs.length < count) return false;
		for (i in 1...count + 1) {
			if (logs[logs.length - i].event.type != type) return false;
		}
		return true;
	}

	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', Main.jsonStringify(getLogs(), "\t"));
	}

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

	function removeOldestLog(folder:String):Void {
		final names = FileSystem.readDirectory(folder).filter(name -> {
			if (FileSystem.isDirectory('$folder/$name')) return false;
			if (name.startsWith(".")) return false;
			return name.endsWith(".json");
		});
		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