Logging (Java SDK V2)

Updated at:

Call the PutBucketLogging, GetBucketLogging, and DeleteBucketLogging operations of OSS Java SDK V2 to set, query, and delete logging configurations for a bucket.

Prerequisites

  • OSS Java SDK V2 installed. If you use Maven, add the dependency com.aliyun:alibabacloud-oss-v2 to the pom.xml file.

  • Access credentials configured by using environment variables. The sample code in this topic uses EnvironmentVariableCredentialsProvider to read credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

Permissions

An Alibaba Cloud account has all permissions by default. RAM users and RAM roles created under the account have no permissions by default. The Alibaba Cloud account or an account administrator must grant the required permissions.

API

Action

Description

PutBucketLogging

oss:PutBucketLogging

Sets, queries, or deletes logging configurations.

Sample code

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.OSSClientBuilder;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.models.*;

public class BucketLoggingSample {
    public static void main(String[] args) throws Exception {
        String region = "cn-hangzhou";
        String bucket = "examplebucket";

        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
        OSSClientBuilder clientBuilder = OSSClient.newBuilder()
                .credentialsProvider(provider)
                .region(region);

        try (OSSClient client = clientBuilder.build()) {
            // Set the logging configuration
            LoggingEnabled loggingEnabled = LoggingEnabled.newBuilder()
                    .targetBucket("examplebucket")
                    .targetPrefix("access-log/")
                    .build();

            BucketLoggingStatus loggingStatus = BucketLoggingStatus.newBuilder()
                    .loggingEnabled(loggingEnabled)
                    .build();

            PutBucketLoggingResult putResult = client.putBucketLogging(
                    PutBucketLoggingRequest.newBuilder()
                            .bucket(bucket)
                            .bucketLoggingStatus(loggingStatus)
                            .build());

            System.out.printf("PutBucketLogging status code:%d%n", putResult.statusCode());

            // Query the logging configuration
            GetBucketLoggingResult getResult = client.getBucketLogging(
                    GetBucketLoggingRequest.newBuilder().bucket(bucket).build());

            LoggingEnabled logging = getResult.bucketLoggingStatus().loggingEnabled();
            if (logging != null) {
                System.out.printf("Target bucket: %s, prefix: %s%n",
                        logging.targetBucket(), logging.targetPrefix());
            }

            // Delete the logging configuration
            DeleteBucketLoggingResult delResult = client.deleteBucketLogging(
                    DeleteBucketLoggingRequest.newBuilder().bucket(bucket).build());

            System.out.printf("DeleteBucketLogging status code:%d%n", delResult.statusCode());

        } catch (Exception e) {
            System.out.printf("error:%n%s", e);
        }
    }
}

Configure user-defined log fields

After you enable logging for a bucket, call the PutUserDefinedLogFieldsConfig operation to record specific HTTP request headers and query parameters in the logs. OSS encodes the configured information and writes it to the user_defined_log_fields field of the logs. The field value is the Base64-encoded text of a JSON object, which contains the truncated, headers, and querys fields. These fields indicate whether the data is truncated and which request headers and query parameters are configured.

  • Header fields: specified by using the headers parameter of LoggingHeaderSet. Header names must comply with the HTTP protocol and consist of only printable ASCII characters (33 to 126). Periods (.) are supported, but colons (:) and underscores (_) are not. Use hyphens (-) instead of underscores.

  • Parameter fields: specified by using the parameters parameter of LoggingParamSet. Query parameter names support underscores (_).

  • The total number of custom request headers and query parameters cannot exceed 6. The total length of the keys and values of custom fields cannot exceed 1,024 bytes. Data that exceeds this limit is truncated.

Note

The user-defined log fields feature is supported in OSS Java SDK V2 0.2.0-beta and later. Use the latest version of the SDK.

Sample code

The following code configures user-defined log fields:

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.OSSClientBuilder;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.models.*;

import java.util.Arrays;

public class PutUserDefinedLogFieldsConfigSample {
    public static void main(String[] args) {
        String region = "cn-hangzhou";
        String bucket = "examplebucket";

        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
        OSSClientBuilder clientBuilder = OSSClient.newBuilder()
                .credentialsProvider(provider)
                .region(region);

        try (OSSClient client = clientBuilder.build()) {
            // Configure custom header fields and parameter fields
            LoggingHeaderSet headerSet = LoggingHeaderSet.newBuilder()
                    .headers(Arrays.asList("user-agent"))
                    .build();

            LoggingParamSet paramSet = LoggingParamSet.newBuilder()
                    .parameters(Arrays.asList("user"))
                    .build();

            UserDefinedLogFieldsConfiguration configuration =
                    UserDefinedLogFieldsConfiguration.newBuilder()
                            .headerSet(headerSet)
                            .paramSet(paramSet)
                            .build();

            PutUserDefinedLogFieldsConfigResult result = client.putUserDefinedLogFieldsConfig(
                    PutUserDefinedLogFieldsConfigRequest.newBuilder()
                            .bucket(bucket)
                            .userDefinedLogFieldsConfiguration(configuration)
                            .build());

            System.out.printf("Status code:%d, request id:%s%n",
                    result.statusCode(), result.requestId());
        } catch (Exception e) {
            System.out.printf("error:%n%s", e);
        }
    }
}

To query the user-defined log fields configuration, call client.getUserDefinedLogFieldsConfig(GetUserDefinedLogFieldsConfigRequest.newBuilder().bucket(bucket).build()). To delete the configuration, call client.deleteUserDefinedLogFieldsConfig(DeleteUserDefinedLogFieldsConfigRequest.newBuilder().bucket(bucket).build()).

References