forked from lassenordahl/synesthizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyLogger.java
68 lines (56 loc) · 1.87 KB
/
MyLogger.java
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
package com.cs122b.utils;
import java.io.FileInputStream;
import java.io.*;
import java.io.IOException;
import java.io.FileWriter;
import java.io.File;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
public class MyLogger {
private static boolean initiated = false;
private static File loggerFile;
private static String fileName;
private static void initLogger() {
fileName = "tstjlogs.log";
try {
loggerFile = new File(fileName);
loggerFile.createNewFile();
System.out.println(loggerFile.getAbsolutePath());
} catch (IOException e) {
System.out.println("Error Creating the Log File");
}
}
public static void log(String message){
if (initiated == false) {
initiated = true;
initLogger();
}
// try {
// logger.write(message + "\n");
// System.out.println("writing to file");
// logger.close();
// } catch (IOException e) {
// System.out.println("Error writing to the file");
// }
try {
RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
FileChannel channel = stream.getChannel();
FileLock lock = null;
try {
lock = channel.tryLock();
} catch (final OverlappingFileLockException e) {
stream.close();
channel.close();
System.out.println("could not get lock");
}
stream.seek(stream.length());
stream.writeChars(message + "\n");
lock.release();
stream.close();
channel.close();
} catch(IOException e) {
System.out.println("Error Writing to File");
}
}
}