Skip to content

Instantly share code, notes, and snippets.

@bseib
Last active March 6, 2016 22:24
Show Gist options
  • Save bseib/10f193aa61ca10dc24c2 to your computer and use it in GitHub Desktop.
Save bseib/10f193aa61ca10dc24c2 to your computer and use it in GitHub Desktop.
Dirt-simple output formatting, logback style.
package util;
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Broc Seib
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
/**
* Log to stdout, or format to string in the style of logback.
*
* Example:
*
* int foo = 42;
* String bar = "Harry's";
* Out.log("I was {} when I first went to {}.", foo, bar);
*
* // output is "I was 42 when I first went to Harry's."
*
* If you want to have a literal "{}" in your output, then you're wanting too much
* from this code. If you want output to go somewhere besides stdout, you also want
* to much from this code. This code is meant for quick and dirty testing, and not
* as a real logging mechanism.
*
* @author bseib
*
*/
public class Out {
static public void log(String format, Object... args) {
System.out.println(str(format, args));
}
static public String str(String format, Object... args) {
if ( null == format ) {
return "";
}
int len = format.length();
if ( len < 2 ) {
return format;
}
StringBuilder buf = new StringBuilder();
int argIndex = 0;
int start = 0;
for ( int i=0;i<(len-1);i++) {
if ( (format.charAt(i) == '{') && (format.charAt(i+1) == '}') ) {
if ( start != i ) {
buf.append(format.substring(start, i));
}
if ( argIndex < args.length ) {
buf.append((null==args[argIndex])?"null":args[argIndex].toString());
}
start = i + 2;
argIndex++;
i = i + 1; // skip checking the '}' char that we know follows
}
}
if ( start < len ) {
buf.append(format.substring(start, len));
}
return buf.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment