Categories
discuss

Where does console.log info showup for Google Cloud functions

How can I see the console.log prints when I’m running a Google Cloud function? Is there a cloud console?

exports.helloWorld = function helloWorld(req, res) {
  // Example input: {"message": "Hello!"}
  if (req.body.message === undefined) {
    // This is an error case, as "message" is required.
    res.status(400).send('No message defined!');
  } else {
    // Everything is okay.
    console.log(req.body.message);
    res.status(200).send('Success: ' + req.body.message);
  }
};

Answer

Viewing Logs

You can view the Cloud Function logs using either:

// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GCLOUD_PROJECT environment variable. See
// https://googlecloudplatform.github.io/gcloud-node/#/docs/google-cloud/latest/guides/authentication
const Logging = require('@google-cloud/logging');

function getLogEntries () {
  // Instantiates a client
  const logging = Logging();

  const options = {
    pageSize: 10,
    filter: 'resource.type="cloud_function"'
  };

  // Retrieve the latest Cloud Function log entries
  // See https://googlecloudplatform.github.io/gcloud-node/#/docs/logging
  return logging.getEntries(options)
    .then(([entries]) => {
      console.log('Entries:');
      entries.forEach((entry) => console.log(entry));
      return entries;
    });
}

To view logs with the gcloud tool, use the logs read command:

gcloud functions logs read

To view the logs for a specific function, provide the function name as an argument:

gcloud functions logs read <FUNCTION_NAME>

You can even view the logs for a specific execution:

gcloud functions logs read <FUNCTION_NAME> --execution-id EXECUTION_ID

For the full range of log viewing options, view the help for logs read:

gcloud functions logs read -h

Writing Logs

You can use console.log() or console.error().

  • console.log() commands have the INFO log level.
  • console.error() commands have the ERROR log level.
  • Internal system messages have the DEBUG log level.

More info about viewing Cloud Function logs is available here.

Categories
discuss

RxJS detect when observable has been subscribed to

I have a need to detect when an observable (observedEvents) has been subscribed to, and then subscribe to another observable (triggerEvent). I don’t want to subscribe to triggerEvent manually, but only once and when observedEvents has a subscription.

Here is some code explaining what I am looking for:

// This just emits events
let emitting = new EventEmitter();

// This is the main Observable which someone else might
// have access to
let observedEvents = Rx.Observable.merge(
  Rx.Observable.fromEvent(emitting, 'aba'),
  Rx.Observable.fromEvent(emitting, 'bob')
)

// This trigger should get a subscription if observedEvents
// has one, i.e. when I subscribe to observedEvents
// that subscription activates this trigger

// I have made an attempt at this by calling skipUntil
// this however skips one event, but I don't want that
let triggerEvent = Rx.Observable.merge(
  // these actions are things that can
  // happen when the trigger is active
  Rx.Observable.of('a').delay(200),
  Rx.Observable.of('b').delay(400),
  Rx.Observable.of('c').delay(600)
)
.skipUntil(observedEvents);

// Something else should be used to activate trigger
// I don't want to do this part manually
triggerEvent.subscribe(val => {
    console.log(`Do something fancy with ${val}`);
});

//----------------------------------------------------
// Somewhere else in the code...
//----------------------------------------------------
observedEvents.subscribe(evt => {
  console.log(`Some event: ${evt}`);
});
// At this point I want triggerEvent to become active
// because observedEvents has a subscription

setTimeout(() => {
  emitting.emit('bob', 'world');
  setTimeout(() => emitting.emit('aba', 'stackoverflow!'), 500);
}, 200);
<!DOCTYPE html>
<html>
<head>
  <script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/EventEmitter/5.1.0/EventEmitter.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

</body>
</html>

Is this possible?

I hope that explains what I’m looking for.

As I’m writing this, I’m thinking a solution with Subjects is probably what I need. I’m not sure, but I just need a nudge in the right direction or a solution if possible.

Answer

Sure enough I was right about using Subjects. The key was the observers list for Subject. Here is what I finally did:

let emitting = new EventEmitter();
let sub = new Rx.Subject();

// return this to users
let myGlobalSub = sub.merge(Rx.Observable.of(1, 2, 3));

// For internal use
let myObservers = Rx.Observable.fromEvent(emitting, 'evt');

console.log(`The number of subscribers is ${sub.observers.length}`);

// Only do something if myGlobalSub has subscribers
myObservers.subscribe(l => {
  if (sub.observers.length) { // here we check observers
    console.log(l);
  }
});

// Somewhere in the code...
emitting.emit('evt', "I don't want to see this"); // No output because no subscribers

myGlobalSub.subscribe(l => console.log(l)); // One sub

emitting.emit('evt', 'I want to see this'); // Output because of one sub

console.log(`The number of subscribers is ${sub.observers.length}`);
<!DOCTYPE html>
<html lang=en>

<head>
  <script src="https://unpkg.com/rxjs@5.5.11/bundles/Rx.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/EventEmitter/5.2.5/EventEmitter.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
</body>

</html>
Categories
discuss

Buck – java.lang.UnsatisfiedLinkError: couldn’t find “libjni.so”. How to solve it?

A runtime exception is happening after executing the command buck install --run demo_app_android following this tutorial and this sample demo

Then, the following is shown in console

Installing apk on emulator-5554 (null).
[-] PROCESSING BUCK FILES...FINISHED 0.0s [100%] 🐌  File removed
[-] DOWNLOADING... (0.00 B/S AVG, TOTAL: 0.00 B, 0 Artifacts)
[-] BUILDING...FINISHED 0.8s [100%] (1/1 JOBS, 1 UPDATED, 0 [0.0%] CACHE MISS)
[+] INSTALLING...2.1s
Successfully ran install apk //android:demo-app on 1 device(s)
Starting activity com.facebook.buck.demo/.App...
Successfully ran start activity on 1 device(s)

Finally, the device shows a message saying Buck Demo App has stopped The app was successfully installed as I can see it on the apps list but it’s not working

Stacktrace:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.facebook.buck.demo, PID: 7265
    java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.facebook.buck.demo-1/base.apk"],nativeLibraryDirectories=[/data/app/com.facebook.buck.demo-1/lib/x86, /system/lib, /vendor/lib]]] couldn't find "libjni.so"
    at java.lang.Runtime.loadLibrary0(Runtime.java:972)
    at java.lang.System.loadLibrary(System.java:1530)
    at com.facebook.buck.demo.Hello.<init>(Hello.java:13)
    at com.facebook.buck.demo.App.onCreate(App.java:24)
    at android.app.Activity.performCreate(Activity.java:6662)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

Device specs:

  • Native Android Emulator (also, ran it into a real device with same result)
  • Nexus 5 API 24

My computer:

  • MacBook pro mid 2012

Note: Also, this issue was reported directly to the buck repository but no solution was given yet

Any idea about how to solve it?

Answer

Repeating the answer from github:

You need to install Android NDK from here (version 10e) and set ANDROID_NDK_REPOSITORY to the location of the unpacked NDK (see buckconfig section for more info).

For example, if you unpack NDK to ~/tmp/ndk (so that there is a directory ~/tmp/ndk/android-ndk-r10e), you need to set ANDROID_NDK_REPOSITORY to ~/tmp/ndk.

After that delete old cache and rebuild the app:

$ buck kill && rm -rf buck-out
$ buck build demo_app_android
Categories
discuss

How do I guarantee that the interface between two microservices is not broken?

Imagine we have two microservices: client and server. One of the most fundamental features of microservice architecture is an ability to have a separated pipelines for each microservice meaning that we have to be able to deploy them to production independently.

This implies that different microservices may be developed by different teams and some of the features are developed faster on one microservice than on the another. This quite often ends up with the contract (interface) being broken between client and server, so the JSON that the client sends to the server is no more valid.

The question is how to prevent cases where communication between two microservices is broken due to a broken contract between them? What is the best strategy to handle such issues?

Answer

The question is how to prevent cases where communication between two
microservices is broken due to a broken contract between them?

  1. Design of Contract: While you are designing the contract, the server [also called service provider or producer] can not dictate the contract and just say here is the contract for my offering and now go and consume the service. If server has multiple clients (which is usually the case), then multiple clients will give their ‘demands’ for contracts and server will then implement the minimal common aggregate as service offering.

  2. Change In Contract: Service provider should strive to keep the contract as backword compatible in most of the times. However, if contract requires significant change, then it can be handled with spinning up new version of endpoint. In this case, decommissioning of old endpoint of service(e.g. say v1) will not be done immediately. Consumers of service are given notice of this change and given some time to switch over to newer version of contract. (eg. say v2)

You can get more infomration on Martin Fowler’s bliki: https://martinfowler.com/articles/consumerDrivenContracts.html

What is the best strategy to handle such issues?

I think,I have answered the strategies above. However, in terms of tooling, following are some tools that will facilitate the scenario:

  1. Pact: https://docs.pact.io/
  2. Consul:This is service discovery tool, however, if you are adopting microservices, then this will be really useful for dealing with numerous services. https://www.consul.io/
Categories
discuss

Angular4 – post form data to rest api

How is it possible to post form data to an external rest api?

At the moment i have an html form:

<form [formGroup] = "form" (ngSubmit) = "onSubmit(form.value)">
  <input name="name" formControlName="name">
  <input name="first_name" formControlName="first_name">
  <input name="last_name" formControlName="last_name">
  <button type="submit">Save</button>
 </form>

and then i have the function that is handling the submit in my component.ts file:

  onSubmit = function (user) {
    console.log(user);
    //this.http.post('http://xxx/externalapi/add', user);
  }

But how is it possible to post the form data to my external api? And what is the standard of sending form data with angular? Is it just a simple post request with form data as queryParams or is it standard to convert it into JSON. I can modify the api to handle whatever data is sent so thats not a problem.

Answer

Ok, so it turns out i have to add .subscribe() to post for it to do something. Also if i put “user” straight into post request for some reason it sends an request with method “OPTIONS” without a body. So i have to create a queryParams string myself. If anyone can explain this or show a better way to do this i would appriciate it. Otherwise this currently works:

 onSubmit = function (user) {
    console.log(user);

    var body = "firstname=" + user.firstname + "&lastname=" + user.lastname + "&name=" + user.name;
    this.http.post("http://www.testtttt.com", body).subscribe((data) => {});

  }

Edit: another and probably even a better solution is to use JSON.stringify(user) instead of body. But subscribe() is still needed tho.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..