Skip to content

Instantly share code, notes, and snippets.

@ahartzog
Created May 31, 2019 11:44
Show Gist options
  • Save ahartzog/dab4cbf7ba83ee19582f56c969dc43ee to your computer and use it in GitHub Desktop.
Save ahartzog/dab4cbf7ba83ee19582f56c969dc43ee to your computer and use it in GitHub Desktop.
React Native AsyncStorage event logger
import moment from "moment";
import { sendSlackNotification } from "../../functions";
import AsyncStorage from "../../async-storage";
import purgeClientLogs from "./purgeClientLogs";
let currentlyWriting;
const awaitUntilDoneSubmitting = async () =>
new Promise(resolve => {
const timerCheckSubmitted = setInterval(() => {
if (!currentlyWriting) {
// console.log('All clear to write anew...');
resolve();
clearInterval(timerCheckSubmitted);
} else {
// console.log('Tried workout submit while another ongoing, polling...');
}
}, 100);
});
const logApiCall = async args => {
const { response, body, query, url, forceLog = false } = args;
// Skip it ifs a normal API call and has no body AND no query
if (!forceLog && response && response.ok && !body && !query) {
return null;
}
// Waits until any other things are done writing
await awaitUntilDoneSubmitting();
currentlyWriting = true;
try {
const today = moment().format("YYYY-MM-DD");
let todayClientLog = await AsyncStorage.getItem(
`@Nerdfitness:clientLog-${today}`
);
if (!todayClientLog || todayClientLog.length === 0) {
// No entries for today, go ahead and purge back
purgeClientLogs();
todayClientLog = "";
}
// If the log is over 500Kb, stop adding to it to make sure we stay under Android 6Mb AsyncStorage limit
const logSize = todayClientLog.length;
if (logSize.length > 500000) {
sendSlackNotification({
title: "Log file over 500kb",
datetime: new Date().toDateString(),
message: `Client logs too large for: url: ${JSON.stringify(
url
)}, query: ${JSON.stringify(query)}, body: ${JSON.stringify(
body
)}, length: ${logSize}`,
env: "LogApiCall function",
platformName: "CMA"
});
return null;
}
const callObject = {
...args,
timestamp: new Date().toISOString()
};
todayClientLog =
todayClientLog === ""
? JSON.stringify(callObject)
: `${todayClientLog},${JSON.stringify(callObject)}`;
await AsyncStorage.setItem(
`@Nerdfitness:clientLog-${today}`,
todayClientLog
);
} catch (e) {
console.log("Error appending item to client logs: ", e);
} finally {
currentlyWriting = false;
}
return null;
};
export default logApiCall;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment