Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added annotations package for annotation metrics #152

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,12 @@ config.setShouldWriteToStdout(true);
AWS_EMF_WRITE_TO_STDOUT="true"
```

## Annotations

This library includes a package implmenting annotations that log metrics about method behaviour. This package was seperated so that it can be optionally imported because it adds a large dependency.

Please see the [README](annotations/README.md) in the annotations project folder to learn more.

## Thread-safety

### Internal Synchronization
Expand Down
75 changes: 75 additions & 0 deletions annotations/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Annotations
lksfrnz marked this conversation as resolved.
Show resolved Hide resolved

## Setup

Getting this package to work requires the following additions to a gradle build file:
```gradle
plugins {
...
id "io.freefair.aspectj.post-compile-weaving" version "6.4.3"
}

dependencies {
...
implementation project(':annotations')
implementation "org.aspectj:aspectjweaver:1.9.8.RC3"
}

```

## Usage

This pacakge adds `@CountMetric` and `@ExecutionTimeMetric` method annotations.

### @CountMetric
@CountMetric will log a value of 1 whenever it is triggered.

### @ExecutionTimeMetric
@ExecutionTimeMetric will log the execution time of a method whenever it is triggered.

### Annotation Parameters

- `String Name` (Default: `""`)
- The name the metric is published under
- If the name is left as `""` it will be replaced with `"<ClassName>.<MethodName>.<AnnotationType>"` when being sent to CWL
- `Boolean logSuccess` (Default `True` )
- Determines if this annotation will log a metric when the method exits successfully
- `Class<? extends Throwable>[] LogErrors` (Default: `[Throwable.class]` )
- Determines if this annotation will log a metric when the method exits with an error (will log if the method exits by a throwing an in the given list)
- `String Logger` (Default: `""`)
- Determines which logger this annotation’s metric will be put into.
- If `null` or there is no logger associated with that key then the default logger will be used
- `bool flush` (Default: `false` )
- Determines whether the metric logger attached to this annotation should flush after this function


### Loggers
This package also implements a singleton `MetricAnnotationMediator` which handles the logging of all metrics created by annotations. This singleton contains a default `MetricsLogger` instance that all annotations will default to; however, other loggers can be added to it using its `addLogger(name, logger)` method. Annotations can then be sent to the added logger by specifying the name of the logger as an annotation parameter.

There are two ways to flush these metrics to CloudWatch:
1. Call `MetricAnnotationMediator.flushAll()` which flushes all the loggers that the singleton has a reference to
2. Flush the logger that the metrics have been added to. Loggers can be retrieved from the `MetricAnnotationMediator` using the methods `MetricAnnotationMediator.getDefaultLogger()` and `MetricAnnotationMediator.getLogger(name)`

```java
import software.amazon.cloudwatchlogs.emf.annotations.CountMetric;
import software.amazon.cloudwatchlogs.emf.annotations.ExecutionTimeMetric;
import software.amazon.cloudwatchlogs.emf.annotations.MetricAnnotationMediator;

class Example {

@CountMetric
@ExecutionTimeMetric
public static void doSomething() {
// Do something
...
}

public static void main(String[] args) {
MetricsLogger metrics = new MetricsLogger();

doSomething();

MetricAnnotationMediator.flushAll();
}
}
```
70 changes: 70 additions & 0 deletions annotations/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
plugins {
id 'java'
id 'java-library'
id "io.freefair.aspectj.post-compile-weaving" version "6.4.3"
id 'com.diffplug.spotless' version '5.8.2'
}

repositories {
jcenter()
mavenCentral()
}

dependencies {
implementation rootProject

annotationProcessor 'org.projectlombok:lombok:1.18.24'
compileOnly 'org.projectlombok:lombok:1.18.12'

implementation "org.aspectj:aspectjrt:1.9.22"
implementation "org.aspectj:aspectjweaver:1.9.8.RC3"

implementation 'com.fasterxml.jackson.core:jackson-core:2.14.2'
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.14.2'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.2'
implementation 'org.slf4j:slf4j-api:2.0.6'
implementation 'org.javatuples:javatuples:1.2'
implementation 'org.apache.commons:commons-lang3:3.12.0'

// Use JUnit test framework
testImplementation 'software.amazon.awssdk:cloudwatch:2.20.13'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.2'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.2'
testImplementation 'org.junit.vintage:junit-vintage-engine:5.9.2'
testImplementation 'org.mockito:mockito-core:2.+'
testImplementation 'org.powermock:powermock-module-junit4:2.0.9'
testImplementation 'org.powermock:powermock-api-mockito2:2.0.9'
testImplementation 'com.github.javafaker:javafaker:1.0.2'
testImplementation 'com.github.tomakehurst:wiremock-jre8:2.35.0'
testCompileOnly 'org.projectlombok:lombok:1.18.26'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.26'
}

compileTestJava.ajc.options.aspectpath.from sourceSets.main.output

compileJava {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}

spotless {
format 'misc', {
target '*.gradle', '*.md', '.gitignore'

trimTrailingWhitespace()
indentWithTabs()
endWithNewline()
}

java {
importOrder()
googleJavaFormat('1.7').aosp()
removeUnusedImports()
}
}

test {
outputs.upToDateWhen {false}
useJUnitPlatform()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package software.amazon.cloudwatchlogs.emf.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* This annotation is used to put a count metric to CloudWatch Metrics. By default, when the
* annotated method is called, the value 1.0 will be published with the metric name
* "[ClassName].[methodName].Count". The value and metric name can be overridden, and the "applies"
* field can be used to only publish for invocations when failures are/aren't thrown by the
* annotated method.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Repeatable(CountMetrics.class)
public @interface CountMetric {
String name() default "";

boolean logSuccess() default true;

Class<? extends Throwable>[] logExceptions() default {Throwable.class};

double value() default 1.0d;

String logger() default "_defaultLogger";

boolean flush() default false;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package software.amazon.cloudwatchlogs.emf.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** Allows multiple {@link CountMetric} annotations on a single method. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CountMetrics {
CountMetric[] value();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package software.amazon.cloudwatchlogs.emf.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* This annotation is used to put a duration metric to CloudWatch Metrics. By default, when the
* annotated method is called, the duration (in milliseconds) will be published with the metric name
* "[ClassName].[methodName].Time". The metric name can be overridden, and the "applies" field can
* be used to only publish for invocations when failures are/aren't thrown by the annotated method.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Repeatable(ExecutionTimeMetrics.class)
public @interface ExecutionTimeMetric {
String name() default "";

boolean logSuccess() default true;

Class<? extends Throwable>[] logExceptions() default {Throwable.class};

String logger() default "_defaultLogger";

boolean flush() default false;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package software.amazon.cloudwatchlogs.emf.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** Allows multiple {@link ExecutionTimeMetric} annotations on a single method. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExecutionTimeMetrics {
ExecutionTimeMetric[] value();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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
*
* http://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.
*/

package software.amazon.cloudwatchlogs.emf.annotations;

import java.util.HashMap;
import software.amazon.cloudwatchlogs.emf.logger.MetricsLogger;

/** */
public class MetricAnnotationMediator {
public static MetricAnnotationMediator getInstance() {
return SINGLETON;
}

private static final MetricAnnotationMediator SINGLETON = new MetricAnnotationMediator();

private static final String defaultLoggerKey = "_defaultLogger";

// protected instead of private for testing purposes
static HashMap<String, MetricsLogger> loggers;

private MetricAnnotationMediator() {
loggers = new HashMap<>();
loggers.put(defaultLoggerKey, new MetricsLogger());
}

/** @return the default logger this singleton uses */
public static MetricsLogger getDefaultLogger() {
return loggers.get(defaultLoggerKey);
}

/**
* @param name the name of the logger to get
* @return the logger with the specified name if it exists, otherwise will return the default
* logger
* @see MetricAnnotationMediator#getDefaultLogger() getDefaultLogger()
*/
public static MetricsLogger getLogger(String name) {
if (name.isEmpty()) {
return getDefaultLogger();
}
return loggers.getOrDefault(name, getDefaultLogger());
}

/**
* Adds a logger to this singleton if no other logger has the same name.
*
* @param name the desired name of the logger
* @param logger the logger to be added
* @return true if the logger was successfully added and false if annother logger already has
* the same name
*/
public static boolean addLogger(String name, MetricsLogger logger) {
if (loggers.containsKey(name)) {
return false;
}

loggers.put(name, logger);
return true;
}

/** Flushes all loggers added to this singleton */
public static void flushAll() {
for (MetricsLogger logger : loggers.values()) {
logger.flush();
}
}
}
Loading