参考文档:
1.阿里云日志服务器Android SDK
2.Android Demo
3.中文版
4.STS方式
1.添加jar包
把demo里面的jar包拷进自己项目,日志服务 Android SDK依赖于fastjson,greenDAO。
compile 'com.alibaba:fastjson:1.2.35'
compile 'org.greenrobot:greendao:3.2.2'
compile files('libs/aliyun-log-sdk-android-2.1.0.jar')
2.添加权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
3.在application中初始化
import com.aliyun.sls.android.sdk.SLSDatabaseManager;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
SLSDatabaseManager.getInstance().setupDB(getApplicationContext());
}
}
然后在AndroidManifest.xml中<application android:name=".XXApplication /application>"
4.向app服务器请求accessKeyId,secretKeyId,securityToken
1.应用向用户的应用服务器申请一个临时访问凭证。
Android/iOS应用不能直接存储AccessKeyID/AccessKeySecret,这样会存在泄密的风险。所以应用必须向用户的应用服务器申请一个临时上传凭证(下文将此临时上传凭证称为Token)。这个Token是有时效性的,如果这个Token的过期时间是30分钟(这个时间可以由应用服务器指定),那么在这30分钟里面,该Android/iOS应用可以使用这个Token访问日志服务, 30分钟后再重新获取。
2.用户的应用服务器检测上述请求的合法性,然后返回Token给应用。
3.手机拿到这个Token后就可以访问日志服务了。
app服务器返回的数据格式样式:
//正确返回
{
"StatusCode":200,
"AccessKeyId":"STS.3p***dgagdasdg",
"AccessKeySecret":"rpnwO9***tGdrddgsR2YrTtI",
"SecurityToken":"CAES+wMIARKAAZhjH0EUOIhJMQBMjRywXq7MQ/cjLYg80Aho1ek0Jm63XMhr9Oc5s˙∂˙∂3qaPer8p1YaX1NTDiCFZWFkvlHf1pQhuxfKBc+mRR9KAbHUefqH+rdjZqjTF7p2m1wJXP8S6k+G2MpHrUe6TYBkJ43GhhTVFMuM3BZajY3VjZWOXBIODRIR1FKZjIiEjMzMzE0MjY0NzM5MTE4NjkxMSoLY2xpZGSSDgSDGAGESGTETqOio6c2RrLWRlbW8vKgoUYWNzOm9zczoqOio6c2RrLWRlbW9KEDExNDg5MzAxMDcyNDY4MThSBTI2ODQyWg9Bc3N1bWVkUm9sZVVzZXJgAGoSMzMzMTQyNjQ3MzkxMTg2OTExcglzZGstZGVtbzI=",
"Expiration":"2017-11-12T07:49:09Z",
}
//错误返回
{
"StatusCode":500,
"ErrorCode":"InvalidAccessKeyId.NotFound",
"ErrorMessage":"Specified access key is not found."
}
5.初始化LOGClient
StsTokenCredentialProvider credentialProvider =
new StsTokenCredentialProvider(accessKeyId, secretKeyId, securityToken);
com.aliyun.sls.android.sdk.ClientConfiguration conf = new com.aliyun.sls.android.sdk.ClientConfiguration();
conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个
conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
conf.setCachable(false);
conf.setConnectType(com.aliyun.sls.android.sdk.ClientConfiguration.NetworkPolicy.WWAN_OR_WIFI);
SLSLog.enableLog(); // log打印在控制台
logClient = new LOGClient(AppApplication.getContext(), endpoint, credentialProvider, conf);
注意LOGClient的生命周期和app保持一致。
6.异步发送日志
// 1. 创建logGroup
LogGroup logGroup = new LogGroup("sls test", TextUtils.isEmpty(ip) ? " no ip " : ip);
// 2. 创建一条log
Log log = new Log();
log.PutContent("current time ", "" + System.currentTimeMillis() / 1000);
log.PutContent("content", "this is a log");
// 3. 将log加入到group
logGroup.PutLog(log);
// 4. 发送log到sls服务器
try {
PostLogRequest request = new PostLogRequest(project, logStore, logGroup);
logClient.asyncPostLog(request, new CompletedCallback<PostLogRequest, PostLogResult>() {
@Override
public void onSuccess(PostLogRequest request, PostLogResult result) {
Message message = Message.obtain(handler);
message.what = HANDLER_MESSAGE_UPLOAD_SUCCESS;
message.sendToTarget();
}
@Override
public void onFailure(PostLogRequest request, LogException exception) {
Message message = Message.obtain(handler);
message.what = HANDLER_MESSAGE_UPLOAD_FAILED;
message.obj = exception.getMessage();
message.sendToTarget();
}
});
} catch (LogException e) {
e.printStackTrace();
}
demo
package com.qingclass.yiban.utils;
import android.content.Context;
import android.os.Message;
import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.aliyun.sls.android.sdk.LOGClient;
import com.aliyun.sls.android.sdk.LogException;
import com.aliyun.sls.android.sdk.SLSLog;
import com.aliyun.sls.android.sdk.core.auth.PlainTextAKSKCredentialProvider;
import com.aliyun.sls.android.sdk.core.auth.StsTokenCredentialProvider;
import com.aliyun.sls.android.sdk.core.callback.CompletedCallback;
import com.aliyun.sls.android.sdk.model.Log;
import com.aliyun.sls.android.sdk.model.LogGroup;
import com.aliyun.sls.android.sdk.request.PostLogRequest;
import com.aliyun.sls.android.sdk.result.PostLogResult;
import com.qingclass.yiban.AppApplication;
import com.qingclass.yiban.api.IHomeApiService;
import com.qingclass.yiban.baselibrary.log.QCLog;
import com.qingclass.yiban.baselibrary.net.NetWorkingHelper;
import com.qingclass.yiban.baselibrary.net.entity.MAPIResult;
import com.qingclass.yiban.common.store.BasicConfigStore;
import com.qingclass.yiban.entity.home.StsBean;
import com.qingclass.yiban.entity.note.BookNoteBean;
import com.qingclass.yiban.ui.activity.home.HomeWriteNotesActivity;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* 姓名:suyan
* 类说明:阿里日志
* <p>
* STS方式: https://help.aliyun.com/document_detail/62681.html
* <p>
* 调用:例如:SLSUtils.getInstance().requestData("测试内容",null);
*/
public class SLSUtils {
private volatile static SLSUtils instance;
public String project = "**********";
public String logStore = "*********";
//client的生命周期和app保持一致,
public LOGClient logClient;
public SLSUtils() {
}
public static SLSUtils getInstance() {
if (instance == null) {//双重锁
synchronized (SLSUtils.class) {
if (instance == null) {
return new SLSUtils();
}
}
}
return instance;
}
/**
* 1.初始化logClient
*
* @param accessKeyId 服务器下发的
* @param secretKeyId 服务器下发的
* @param securityToken 服务器下发的
* @param endpoint 服务器下发的
*/
private void setupSLSClient(String accessKeyId, String secretKeyId, String securityToken, String endpoint) {
QCLog.e("suyan===========5");
StsTokenCredentialProvider credentialProvider =
new StsTokenCredentialProvider(accessKeyId, secretKeyId, securityToken);
com.aliyun.sls.android.sdk.ClientConfiguration conf = new com.aliyun.sls.android.sdk.ClientConfiguration();
conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个
conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
conf.setCachable(false);
conf.setConnectType(com.aliyun.sls.android.sdk.ClientConfiguration.NetworkPolicy.WWAN_OR_WIFI);
SLSLog.enableLog(); // log打印在控制台
logClient = new LOGClient(AppApplication.getContext(), endpoint, credentialProvider, conf);
}
/*
* 2.发送日志
* 推荐使用的方式,直接调用异步接口,通过callback 获取回调信息
*/
private void asyncUploadLog(String accessKeyId, String secretKeyId, String securityToken, String endpoint, String logInfo, final SLSUtils.SLSUpCallback mSLSUpCallback) {
QCLog.e("suyan===========4");
setupSLSClient(accessKeyId, secretKeyId, securityToken, endpoint);
// 1. 创建logGroup
LogGroup logGroup = new LogGroup("sls test", logInfo);
// 2. 创建一条log
Log log = new Log();
log.PutContent("current time ", "" + System.currentTimeMillis() / 1000);
log.PutContent("content", "this is a log");
// 3. 将log加入到group
logGroup.PutLog(log);
// 4. 发送log到sls服务器
try {
PostLogRequest request = new PostLogRequest(project, logStore, logGroup);
logClient.asyncPostLog(request, new CompletedCallback<PostLogRequest, PostLogResult>() {
@Override
public void onSuccess(PostLogRequest request, PostLogResult result) {
if (mSLSUpCallback != null) {
QCLog.e("suyan===========7");
mSLSUpCallback.success();
}
}
@Override
public void onFailure(PostLogRequest request, LogException exception) {
if (mSLSUpCallback != null) {
QCLog.e("suyan===========6");
mSLSUpCallback.failure();
}
}
});
} catch (LogException e) {
e.printStackTrace();
}
}
/**
* 4.上传成功与失败回掉
*/
public interface SLSUpCallback {
void success();
void failure();
}
/**
* 5.向服务器请求阿里日志上传密钥
*/
public void requestData(String loginfo, final SLSUtils.SLSUpCallback mSLSUpCallback) {
NetWorkingHelper.getInstance().getNetService(IHomeApiService.class).getSts("2", BasicConfigStore.getInstance(AppApplication.getContext()).getUserId() + "")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<MAPIResult<StsBean>>() {
@Override
public void onSubscribe(Disposable d) {
QCLog.e("suyan===========1");
}
@Override
public void onNext(MAPIResult<StsBean> result) {
QCLog.e("suyan===========2");
if (result != null && result.isSuccess()) {
StsBean mStsBean = result.getData();
QCLog.e("suyan===========3");
asyncUploadLog(mStsBean.getAccessKeyId(), mStsBean.getAccessKeySecret(), mStsBean.getSecurityToken(), mStsBean.getEndPoint(), loginfo, mSLSUpCallback);
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
网友评论