Spectator是记录多维时间序列的简单插装代码库,要求Java7及以上版本。
代码示例:
// The Spectator class provides a static lookup for the default registryServer s = ew Server(Spectator.registry());public class Server { private fial ExtededRegistry registry; private fial Id requestCoutId; private fial Timer requestLatecy; private fial DistributioSummary resposeSizes; // We ca pass i the registry to make uit testig easier. Outside of tests it should typically // be boud to Spectator.registry() to make sure data goes to the right place. public Server(ExtededRegistry registry) { this.registry = registry; // Create a base id for the request cout. The id will get refied with additioal dimesios // whe we receive a request. requestCoutId = registry.createId("server.requestCout"); // Create a timer for trackig the latecy. The referece ca be held oto to avoid // additioal lookup cost i critical paths. requestLatecy = registry.timer("server.requestLatecy"); // Create a distributio summary meter for trackig the respose sizes. resposeSizes = registry.distributioSummary("server.resposeSizes"); // Gauge type that ca be sampled. I this case it will ivoke the specified method via // reflectio to get the value. The registry will keep a weak referece to the object passed // i so that registratio will ot prevet garbage collectio of the server object. registry.methodValue("server.umCoectios", this, "getNumCoectios"); } public Respose hadle(Request req) { fial log s = System.aoTime(); try { Respose res = doSomethig(req); // Update the couter id with dimesios based o the request. The couter will the // be looked up i the registry which should be fairly cheap, such as lookup of id object // i a CocurretHashMap. However, it is more expesive tha havig a local variable set // to the couter. fial Id ctId = requestCoutId .withTag("coutry", req.coutry()) .withTag("status", res.status()); registry.couter(ctId).icremet(); resposeSizes.record(res.body().size()); retur res; } catch (Exceptio e) { fial Id ctId = requestCoutId .withTag("coutry", req.coutry()) .withTag("status", "exceptio") .withTag("error", e.getClass().getSimpleName()); registry.couter(ctId).icremet(); throw e; } fially { // Update the latecy timer. This should typically be doe i a fially block. requestLatecy.record(System.aoTime() - s, TimeUit.NANOSECONDS); } } public it getNumCoectios() { // however we determie the curret umber of coectios o the server }}
评论