summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorManuel Amago <mamago@gmail.com>2019-09-08 05:44:02 +0100
committerManuel Amago <mamago@gmail.com>2019-09-08 05:44:02 +0100
commit980b7c9fa9a88f7ee3881a4a3c65015da068eb2c (patch)
treebbae578e550e5f5e495a6d656dda4a2880a6f5de
downloadlogging-980b7c9fa9a88f7ee3881a4a3c65015da068eb2c.tar.gz
logging-980b7c9fa9a88f7ee3881a4a3c65015da068eb2c.zip
Initial cut of zero GC logging lib
Cheated by not offloading to async thread yet
-rw-r--r--.gitignore32
-rw-r--r--build.gradle37
-rw-r--r--gradle/wrapper/gradle-wrapper.jarbin0 -> 55616 bytes
-rw-r--r--gradle/wrapper/gradle-wrapper.properties6
-rwxr-xr-xgradlew188
-rw-r--r--gradlew.bat100
-rw-r--r--settings.gradle10
-rw-r--r--src/main/java/org/mamago/logging/Logger.java213
-rw-r--r--src/test/java/org/mamago/logging/LoggerTest.java17
9 files changed, 603 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6873309
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,32 @@
+target
+prop
+out
+
+# OS X
+.DS_Store
+
+# intellij
+.idea
+*.iml
+
+# eclipse
+.project
+.classpath
+.settings
+
+# editors
+*.sublime-project
+*.sublime-workspace
+*~
+
+# the build
+build-local.properties
+.gradle
+build
+
+# Benchmark timings
+timings.log
+
+# JVM crash reports
+hs_err_pid*
+/bin/
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 0000000..6676a6b
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,37 @@
+/*
+ * This file was generated by the Gradle 'init' task.
+ *
+ * This generated file contains a sample Java Library project to get you started.
+ * For more details take a look at the Java Libraries chapter in the Gradle
+ * User Manual available at https://docs.gradle.org/5.6.1/userguide/java_library_plugin.html
+ */
+
+plugins {
+ // Apply the java-library plugin to add support for Java Library
+ id 'java-library'
+}
+
+repositories {
+ // Use jcenter for resolving dependencies.
+ // You can declare any Maven/Ivy/file repository here.
+ mavenCentral()
+}
+
+dependencies {
+ // This dependency is exported to consumers, that is to say found on their compile classpath.
+ api 'org.agrona:agrona:1.0.7'
+
+ // This dependency is used internally, and not exposed to consumers on their own compile classpath.
+// implementation 'com.google.guava:guava:28.0-jre'
+
+ // Use JUnit Jupiter API for testing.
+ testImplementation 'org.junit.jupiter:junit-jupiter-api:5.4.2'
+
+ // Use JUnit Jupiter Engine for testing.
+ testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.4.2'
+}
+
+test {
+ // Use junit platform for unit tests
+ useJUnitPlatform()
+}
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..5c2d1cf
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..c8e083c
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Sun Sep 08 05:36:33 BST 2019
+distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.1-all.zip
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStorePath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..83f2acf
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,188 @@
+#!/usr/bin/env sh
+
+#
+# Copyright 2015 the original author or authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+ echo "$*"
+}
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=$(save "$@")
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
+if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
+ cd "$(dirname "$0")"
+fi
+
+exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..24467a1
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,100 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windows variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/settings.gradle b/settings.gradle
new file mode 100644
index 0000000..34460eb
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1,10 @@
+/*
+ * This file was generated by the Gradle 'init' task.
+ *
+ * The settings file is used to specify which projects to include in your build.
+ *
+ * Detailed information about configuring a multi-project build in Gradle can be found
+ * in the user manual at https://docs.gradle.org/5.6.1/userguide/multi_project_builds.html
+ */
+
+rootProject.name = 'logging'
diff --git a/src/main/java/org/mamago/logging/Logger.java b/src/main/java/org/mamago/logging/Logger.java
new file mode 100644
index 0000000..6610da8
--- /dev/null
+++ b/src/main/java/org/mamago/logging/Logger.java
@@ -0,0 +1,213 @@
+package org.mamago.logging;
+
+import sun.misc.HexDumpEncoder;
+
+import java.nio.ByteBuffer;
+
+import static java.lang.Math.min;
+
+public class Logger {
+ public enum Level {TRACE, DEBUG, INFO, WARN, ERROR}
+ private enum TypeMarker {BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE, CHAR_SEQUENCE, FORMATTABLE}
+
+ private final LogBuilder builder;
+
+ // Factory methods ------------------------------------
+
+ public static Logger createLogger() {
+ return new Logger(getCallerClass());
+ }
+
+ public static Logger createLogger(CharSequence name) {
+ return new Logger(name);
+ }
+
+ // Instance methods -----------------------------------
+
+ private Logger(CharSequence name) {
+ builder = new LogBuilder(name.toString());
+ }
+
+ public LogBuilder log(Level level, CharSequence formatSpec) {
+ return builder.reset(level, formatSpec);
+ }
+
+ // Helper methods --------------------------------------
+
+ private static String getCallerClass() {
+ return Thread.currentThread().getStackTrace()[3].getClassName();
+ }
+
+ private static byte b(int i) {
+ // @Fixme[MA]: check whether casting give out-of-bounds check, otherwise add in for safety
+ return (byte) i;
+ }
+
+ // Helper classes --------------------------------------
+
+ public interface Formattable {
+ void formatTo(ByteBuffer b);
+ }
+
+ public static class LogBuilder implements Appendable {
+ // @Fixme[MA]: buffer needs to be auto-expandable
+ private final ByteBuffer headerBuf = ByteBuffer.allocate(256);
+ private final Header header;
+ // @Fixme[MA]: buffer needs to be auto-expandable
+ private final ByteBuffer buffer = ByteBuffer.allocate(256);
+ private Level level;
+
+ private LogBuilder(CharSequence loggerName) {
+ // @Optimisation[MA]: Write logger name to the header buffer once. Should never have to be written again,
+ // as LogBuilders are not shareable between loggers. In the event of seeing corruption of header buffer
+ // data in the wild can remove this mini-optimisation and just write logger name every time in log() call.
+ // (Though the real question would be: how if the buffer getting corrupted?)
+ header = new Header(loggerName);
+ }
+
+ @Override
+ public LogBuilder append(CharSequence csq) {
+ append(csq, 0, csq.length());
+ return this;
+ }
+
+ @Override
+ public LogBuilder append(CharSequence csq, int start, int end) {
+ buffer.put(b(TypeMarker.CHAR_SEQUENCE.ordinal()));
+ buffer.putInt(end - start); // length
+ for (int i = start; i < end; i++) {
+ append(csq.charAt(i));
+ }
+ return this;
+ }
+
+ @Override
+ public LogBuilder append(char c) {
+ buffer.put(b(TypeMarker.CHAR.ordinal()));
+ buffer.put(b(c));
+ return this;
+ }
+
+ @Deprecated // @Fixme[MA]: really want an annotation to create a compiler warning.
+ public LogBuilder append(String s) {
+ append((CharSequence) s);
+ return this;
+ }
+
+ public LogBuilder append(Formattable f) {
+ buffer.put(b(TypeMarker.FORMATTABLE.ordinal()));
+ // @Fixme[MA]: Implement this!
+ throw new RuntimeException("Not yet implemented");
+// return this;
+ }
+
+ public LogBuilder append(byte b) {
+ buffer.put(b(TypeMarker.BYTE.ordinal()));
+ buffer.put(b);
+ return this;
+ }
+
+ public LogBuilder append(short s) {
+ buffer.put(b(TypeMarker.SHORT.ordinal()));
+ buffer.putShort(s);
+ return this;
+ }
+
+ public LogBuilder append(int i) {
+ buffer.put(b(TypeMarker.INT.ordinal()));
+ buffer.putInt(i);
+ return this;
+ }
+
+ public LogBuilder append(long l) {
+ buffer.put(b(TypeMarker.LONG.ordinal()));
+ buffer.putLong(l);
+ return this;
+ }
+
+ public LogBuilder append(float f) {
+ buffer.put(b(TypeMarker.FLOAT.ordinal()));
+ buffer.putFloat(f);
+ return this;
+ }
+
+ public LogBuilder append(double d) {
+ buffer.put(b(TypeMarker.DOUBLE.ordinal()));
+ buffer.putDouble(d);
+ return this;
+ }
+
+ // @Fixme[MA]: should generate a compiler warning if a log statement is missing the .log() call
+ public void log() {
+ Thread ct = Thread.currentThread();
+ header.timestamp(System.currentTimeMillis()) // @Fixme[MA] Use high precision wall clock
+ .level(level)
+ .threadId(ct.getId()).threadName(ct.getName());
+// logRingBuffer.write(headerBuf, buffer);
+ HexDumpEncoder encoder = new HexDumpEncoder();
+ System.out.println("Header:");
+ headerBuf.position(0).limit(headerBuf.get(0));
+ System.out.println(encoder.encodeBuffer(headerBuf));
+ System.out.println("Args:");
+ System.out.println(encoder.encodeBuffer((ByteBuffer) buffer.flip()));
+ }
+
+ public LogBuilder reset(Level level, CharSequence formatSpec) {
+ this.level = level;
+ buffer.clear();
+ append(formatSpec);
+ return this;
+ }
+
+ // Helper classes ----------------------------------
+
+ // @Speedup[MA]: this implementation just packs everything tight in the header.
+ // It is possible that alignment optimisations may make this faster.
+ private class Header {
+ private final int tsOffset;
+ private final int levelOffset;
+ private final int tidOffset;
+ private final int tNameOffset;
+
+ Header(CharSequence loggerName) {
+ tsOffset = put(1, loggerName);
+ levelOffset = tsOffset + 8;
+ tidOffset = levelOffset + 1;
+ tNameOffset = tidOffset + 8;
+ }
+
+ Header timestamp(long ts) {
+ System.out.println("ts = " + ts);
+ headerBuf.putLong(tsOffset, ts);
+ return this;
+ }
+
+ Header level(Level level) {
+ headerBuf.put(levelOffset, b(level.ordinal()));
+ return this;
+ }
+
+ Header threadId(long tid) {
+ headerBuf.putLong(tidOffset, tid);
+ return this;
+ }
+
+ // Does not return this reference, as this is the terminator for building the header buffer
+ void threadName(CharSequence tName) {
+ // Write header size to first byte
+ headerBuf.put(0, b(put(tNameOffset, tName)));
+ }
+
+ private int put(int offset, CharSequence csq) {
+ // @Optimisation[MA]: CharSequence length as a byte, as we chop header char sequences short (we don't
+ // expect long thread or logger names).
+ int length = min(csq.length(), 50);
+ headerBuf.put(offset++, b(length));
+ for (int i = 0; i < length; i++) {
+ headerBuf.put(offset++, (byte) csq.charAt(i));
+ }
+ return offset;
+ }
+ }
+ }
+}
diff --git a/src/test/java/org/mamago/logging/LoggerTest.java b/src/test/java/org/mamago/logging/LoggerTest.java
new file mode 100644
index 0000000..3a1efbd
--- /dev/null
+++ b/src/test/java/org/mamago/logging/LoggerTest.java
@@ -0,0 +1,17 @@
+package org.mamago.logging;
+
+import org.junit.jupiter.api.Test;
+
+public class LoggerTest {
+ final static Logger LOG = Logger.createLogger();
+
+ @Test
+ public void testLogger() {
+ System.out.println("header length = " +
+ ( 1 // Header length
+ + 1 // Thread name length
+ + LoggerTest.class.getName().length()
+ + 8 + 8 + 1 + "main".length() + 1));
+ LOG.log(Logger.Level.INFO, "Log this {}").append(3).log();
+ }
+}