log4j support in Android - android

I am attempting to shoehorn an existing SDK onto an android device and one of the dependencies of said SDK is Apache log4j. I am able to load my test program onto the android emulator but when the log4j object "PropertySetter" is called the program fails with a verification exception. Is there a way to ameliorate this issue?

Actually using slf4j turned out a remarkably painless process for me, and it seems the common case, at least for libraries that use straightforward log4j features. You don't really need to swap slf4j in for log4j, only add two slf4j libraries to your project from http://www.slf4j.org/download.html:
-- the slf4j library for Android (currently slf4j-android-1.6.1-RC1.jar)
-- the log4j over slf4j (http://www.slf4j.org/legacy.html#log4j-over-slf4j) bridge.
The latter defines the core log4j classes used by typical implementations and bind them to the slf4j Android implementation. Once the libraries are added the code works.

I successfully got log4j working on android with a Socket Appender and Log4j Chainsaw. All code is located in this repository. Slf4j set up and working too. Be aware you have to configure it programmatically. You cannot use .properties or .xml files the parser wont work on android. Enjoy.
https://sourceforge.net/projects/log4j-android/

There is a new project, which enables log4j on android. Also using log4j over slf4j is possible. It also provides an appender for LogCat. See Logging in Android using Log4J.
The following example shows how to configure and use log4j in Android.
Configure the log4j system in Android
import org.apache.log4j.Level;
import android.os.Environment;
import de.mindpipe.android.logging.log4j.LogConfigurator;
/**
* Simply place a class like this in your Android applications classpath.
*/
public class ConfigureLog4J {
static {
final LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(Environment.getExternalStorageDirectory() + "myapp.log");
logConfigurator.setRootLevel(Level.DEBUG);
// Set log level of a specific logger
logConfigurator.setLevel("org.apache", Level.ERROR);
logConfigurator.configure();
}
}
Logging in Android using log4j using slf4j API
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExampleLog4JOverSLF4J {
private final Logger log = LoggerFactory.getLogger(ExampleLog4JOverSLF4J.class);
public void myMethod() {
log.info("This message should be seen in log file and logcat");
}
}
Logging in Android using log4j API
import org.apache.log4j.Logger;
public class ExampleLog4J {
private final Logger log = Logger.getLogger(LogConfiguratorTest.class);
public void myMethod() {
log.info("This message should be seen in log file and logcat");
}
}

I would recommend trying to swap in slf4j in place of log4j. It's not a painless switch but its likely to be easier than what you have. slf4j provides a common front-end for several loggers including log4j and there is an slf4j-android package.
No, Android's logging mechanism is not decent. It's very inadequate compared to what log4j can do for you.

The parser for log4j configuration files is not android safe.slf4j's android compatibility thing with log4j just overrides the log4j classes you will use and forces them to use android logcat style logging. You still don't get the full flexibility of log4j on android. I ported log4j on android in my project https://sourceforge.net/projects/log4j-android/ all you have to do is add the two jars in the binaries directory to you classpath. Then
static {
org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger();
final SocketAppender appender = new SocketAppender("192.168.1.4", 4445);
root.addAppender(appender);
}
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MyClass.class);
static {
logger.info("Hello logger");
}
This will start sending out messages to the remote host you specified. You can then see this messages with Chainsaw http://logging.apache.org/log4j/docs/webstart/chainsaw/chainsawWebStart.jnlp. To make chainsaw work click the second check box on the dialog that pops up hit ok, start your app and a new tab should appear. Be aware your firewall might block it...

Check out this project for a complete implementation: http://code.google.com/p/log4j-android/

Related

AmazonSQSClientBuilder and AWSStaticCredentialsProvider with the Android SDK

I am attempting to implement message sending from my Android app using AWS SQS. I have included aws-android-sdk-core-2.6.15 and aws-android-sdk-sqs-2.6.15 jar files. With just these, I am unable to resolve AmazonSQSClientBuilder (import com.amazonaws.services.sqs.AmazonSQSClientBuilder) and AWSStaticCredentialsProvider (import com.amazonaws.auth.AWSStaticCredentialsProvider).
These work if I include the aws-java-sdk-1.11.278 jar file. However, this causes the 'DuplicateFileException' when I try to build. If I include only this jar, then I get the 'GC overhead limit exceeded' error.
Is there a smaller package that will allow the import of these necessary classes?
Thanks!
The AWS SDK for Android does not follow the same pattern as AWS SDK for Java.
The applicable constructors can be found in these files depending on whether you want an async client or not:
https://github.com/aws/aws-sdk-android/blob/master/aws-android-sdk-sqs/src/main/java/com/amazonaws/services/sqs/AmazonSQSAsyncClient.java
https://github.com/aws/aws-sdk-android/blob/master/aws-android-sdk-sqs/src/main/java/com/amazonaws/services/sqs/AmazonSQSClient.java
One example:
AWSCredentialsProvider awsCredentialsProvider = // Choose one of many classes that implement this for instance, CognitoCachingCredentialsProvider
AmazonSQSClient client = new AmazonSQSClient(awsCredentialsProvider);

Scala reflection java.rmi dependency, can it work on Android?

I would like to use the Scala (2.11) reflection package's runtime mirror in a Scala application compiled for android which is being build using Scala on android.
I was able to fiddle with ProGuard options in order to make it include the required Scala classes. However when I try to get a mirror instance:
universe.runtimeMirror(this.getClass.getClassLoader)
(Indeed it fails during the lazy computation of universe)
The application crashes in run time:
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/rmi/Remote;
at scala.reflect.internal.Definitions$DefinitionsClass.RemoteInterfaceClass$lzycompute(Definitions.scala:370)
at scala.reflect.internal.Definitions$DefinitionsClass.RemoteInterfaceClass(D efinitions.scala:370)
at scala.reflect.runtime.JavaUniverseForce$class.force(JavaUniverseForce.scal a:255)
at scala.reflect.runtime.JavaUniverse.force(JavaUniverse.scala:16)
at scala.reflect.runtime.JavaUniverse.init(JavaUniverse.scala:147)
at scala.reflect.runtime.JavaUniverse.<init>(JavaUniverse.scala:78)
at scala.reflect.runtime.package$.universe$lzycompute(package.scala:17)
at scala.reflect.runtime.package$.universe(package.scala:17)
This crash is for me as expected as it isn't:
It is expected as java.rmi is not part of the Android API and I should expect any code trying to load its classes to crash.
It is unexpected as I didn't know that Scala's reflect package used java.rmi
I have traced the code to were rmi is required, that is to JavaUniverse (a trait mixed in JavaUniverse class) force method:
...
definitions.RemoteInterfaceClass
...
Which leads to DefinitionsClass:
lazy val RemoteInterfaceClass = requiredClass[java.rmi.Remote]
Am I wrong to think that this is a no-go for Scala reflection in Android?
If I am, what could be a workaround to this problem?
To summarize your solution and a related solution, it is sufficient to add two files, and modify build.sbt to include:
dexAdditionalParams in Android += "--core-library"
Add java/rmi/Remote.java to your project with the content:
package java.rmi;
public interface Remote {}
Add java/rmi/RemoteException.java to your project with the content:
package java.rmi;
public interface RemoteException {}

aspectj with android, aspect never called

In the project I'm working we've recently added some level of security, now i don't want to have to rewrite the entire nework logic if it can be done much more easily with AOP.
So, I'm trying to intercept the "onRequestSuccess" method of the requestListeners that are used throughout the application.
For this I have made a simple aspect:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class NetworkResponseAspect {
#Around("execution(public void *.onRequestSuccess(..))")
public void intercept(ProceedingJoinPoint joinPoint){
System.out.println("call intercepted " + joinPoint);
try {
joinPoint.proceed();
} catch (Throwable e) {
System.out.println("wut");
}
}
}
I've added the aspectj weaver dependency: compile 'org.aspectj:aspectjweaver:1.8.6'
And it seems to work, at least the annotations are recognized by android studio.
I've placed a breakpoint on the "joinpoint.proceed()" call and started the application in debug mode.
But when I log in (an action that triggers one such listener) nothing happens. Am I missing something?
In Maven you would use AspectJ Maven Plugin (current version is 1.7), in Gradle something similar. This is what you need for compilation if you want to use CTW (compile-time weaving). Those plugins should already contain a dependency on aspectjtools.jar which contains the AspectJ compiler and other stuff. If you use CTW, you need aspectjrt.jar (AspectJ runtime) as a default-scoped (compile) or dependency because it is needed during runtime as well.
If you want to use load-time weaving (LTW), though, you need aspectjweaver.jar on your JVM command line via -javaagent:... because the weaving agent needs to hook into class-loading before your first application class is loaded. P.S.: The weaving agent also contains the AspectJ runtime classes, so you do not need an additional dependency on the runtime in this case.

Generate Cloud Endpoint Client Library in Android Studio using Entity Class Design Pattern

While following the steps outlined here :
https://cloud.google.com/developers/articles/how-to-build-mobile-app-with-app-engine-backend-tutorial/
for creating a cloud endpoint, but using Android Studio instead of Eclipse, I am stuck at Step 9 of the Entity Class Design Pattern as described here :
https://cloud.google.com/developers/articles/how-to-build-mobile-app-with-app-engine-backend-tutorial/#ecdp
In Eclipse, there is a right-click-menu-option for "Generate Cloud Endpoint Client library" when you right-click on the app engine project. However, there is no equivalent option in Android Studio (v1.0.0)
Is this an omission on Google's part or am I missing something.
What is the best workaround for generating the cloud endpoint client library from within Android Studio.
Is there a way to do it from the command-line?
I did find the steps for gradle here :
https://cloud.google.com/appengine/docs/java/endpoints/endpoints_tool
and here :
https://cloud.google.com/appengine/docs/java/endpoints/consume_android
but these are much more time-consuming than the single-step process described in the original link for eclipse.
As stated above the libraries are auto-compiled for you, the other point to note that had me confused is where to get the Builder from.
Now as of Android Studio 1.0.1 the original Eclipse instructions are a little out of date for this as well, the "Builder" is no longer buried into the Endpoint class you make. Instead it is rolled into a separate API class to describe the Builder and associated code.
See: https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints
Endpoint Usage from Android would now look like this:
/* OLD
MyEndpoint.Builder builder = ... */
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
We're working on updating that shopping kart sample to use Android Studio.
In the meantime the documentation for generating endpoints in AS can be found here https://cloud.google.com/tools/android-studio/
There is no 'Generate Cloud Endpoint Client Library' task anymore since it's not needed in the Android Studio workflow. Simply building the project will ensure that the client libraries are available to your android app.
Check out the docs for the appengine gradle plugin https://github.com/GoogleCloudPlatform/gradle-appengine-plugin if you want to be able to manually perform some of the endpoint client library steps from the command line using Gradle.
As Lucien Murray-Pitts explained, the Builder is not in the Endpoint class but in a auto-generated XXXXApi class.
Imagine your java bean is a class called Portfolio under package com.example.backend
You have to add the following import in the AsyncTask class:
import com.example.backend.portfolioApi.PortfolioApi;
and then you can do
PortfolioApi.Builder builder = new PortfolioApi.Builder(....

Android: Can't get logs with SLF4J-Android

I'm building a really simple Android project in ADT and using Maven. I have included both the slf4j-api and slf4j-android dependencies and I can see that everything is compiling properly. However, when I run or debug the application on my Nexus One, I don't see any log output. Is there a specific place I should be looking for these logs or should they be coming out in the Eclipse console?
For reference, here's my main activity:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.app.ListActivity;
import android.os.Bundle;
public class HomeActivity extends ListActivity {
private static Logger logger = LoggerFactory.getLogger(HomeActivity.class);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
logger.debug("onCreate");
}
}
Android by default tells slf4j-android to not to log debug messages, and log4j is polite enough to honor that. Use the impolite https://github.com/mvysny/slf4j-handroid instead :)
I use slf4j as well for logging. The log output shows up on the LogCat window. I'm not sure if there's a way to see it in the Eclipse console. In the Eclipse top-level menu, navigate to: Window -> Show View -> Other. When the dialog appears, expand "Android", and select "LogCat". It doesn't show up by default, unfortunately.
HTH,
Kevin
You may want to have a look at using slf4j together with android-logging-log4j. Also see log4j support in Android.

Categories

Resources